servlet 攔截器,struts2 攔截器_Struts 2攔截器示例

 2023-11-19 阅读 25 评论 0

摘要:struts2 攔截器Welcome to Struts 2 Interceptor Example. While working on Struts 2, most of the time you will spend on Action Classes but Interceptors are the backbone of Struts 2 Framework. 歡迎使用Struts 2攔截器示例。 在Struts 2上工作時,大多數時候您

struts2 攔截器

Welcome to Struts 2 Interceptor Example. While working on Struts 2, most of the time you will spend on Action Classes but Interceptors are the backbone of Struts 2 Framework.

歡迎使用Struts 2攔截器示例。 在Struts 2上工作時,大多數時候您將花在Action Class上,但是Interceptor是Struts 2 Framework的基礎。

Struts 2攔截器 (Struts 2 Interceptor)

Struts 2 interceptors are responsible for most of the processing done by the framework. For example, passing request params to action classes, making Servlet API request, response, session available to Action classes, validation, i18n support etc.

servlet 攔截器, Struts 2攔截器負責框架完成的大多數處理。 例如,將請求參數傳遞給動作類,使Servlet API請求,響應,會話可用于動作類,驗證,i18n支持等。

Struts 2 provides a bunch of interceptors and most of them are defined in struts-default package and used in defaultStack interceptor stack. Interceptors are the power of Struts 2 framework that plays a crucial role in achieving high level of separation of concerns.

Struts 2提供了一堆攔截器,其中大多數是在struts-default包中定義的,并在defaultStack攔截器堆棧中使用。 攔截器是Struts 2框架的強大功能,在實現關注點的高度分離方面起著至關重要的作用。

In our Struts 2 Beginners Tutorial, we looked at the Struts 2 architecture and saw that every request and response passes through interceptors. Hence interceptors can inject different objects, perform specific operations on request and response and do some cross cutting tasks for the application.

在《 Struts 2初學者教程》中 ,我們研究了Struts 2架構,并看到每個請求和響應都通過攔截器傳遞。 因此,攔截器可以注入不同的對象,根據請求和響應執行特定的操作,并為應用程序執行一些交叉任務。

攔截器的工作原理,ActionInvocation is responsible to incapsulate Action classes and interceptors and to fire them in order. The most important method for use in ActionInvocation is invoke() method that keeps track of the interceptor chain and invokes the next interceptor or action. This is one of the best example of Chain of Responsibility pattern in Java EE frameworks.

ActionInvocation負責封裝Action類和攔截器,并按順序觸發它們。 在ActionInvocation中使用的最重要的方法是invoke()方法,該方法跟蹤攔截器鏈并調用下一個攔截器或操作。 這是Java EE框架中“責任鏈”模式的最佳示例之一。

Struts 2 API reads the interceptors defined for an action in the order it’s declared. So if interceptor1 and interceptor2 are defined for action1 then ActionInvocation will invoke them in following chain.

Struts 2 API按照聲明的順序讀取為操作定義的攔截器。 因此,如果為action1定義了interceptor1和interceptor2,則ActionInvocation將在隨后的鏈中調用它們。

interceptor1 -> interceptor2 -> action1 -> interceptor2 -> interceptor1

struts2, 攔截器1->攔截器2->動作1->攔截器2->攔截器1

If any of the interceptor intercept() method decides that action should not get executed, it can return a string value and response will be created from global result with that name from struts configuration file.

如果任何攔截器intercept()方法確定不應執行該操作,則它可以返回一個字符串值,并且將從struts配置文件中具有該名稱的全局結果中創建響應。

Struts 2攔截器和全局結果配置 (Struts 2 Interceptors and Global Results configuration)

We can define global results in struts.xml file as:

我們可以在struts.xml文件中將全局結果定義為:

<global-results><result name="login" type="redirect">/login.action</result>
</global-results>

struts過濾器?These results can be used by any of the action classes.

這些結果可以被任何動作類使用。

Defining interceptors for a package includes several steps and we need to define them with interceptors, interceptor, interceptor-stack and default-interceptor-ref elements. They should be the first elements of the package or else you will get error message as

為包定義攔截器包括幾個步驟,我們需要使用攔截器,攔截器,攔截器堆棧和默認攔截器-ref元素對其進行定義。 它們應該是包的第一個元素,否則您將收到以下錯誤消息:


interceptor-ref?,default-action-ref?,default-class-ref?,global-results?,global-exception-
攔截器參考?,默認動作參考?,默認類參考?,全局結果?,全局異常-
mappings?,action*)”.
映射?,動作*)”。

Struts 2攔截器示例 (Struts 2 Interceptor Example)

A simple example of interceptor configuration is:

struts? 攔截器配置的一個簡單示例是:

<package name="user" namespace="/" extends="struts-default"><interceptors><interceptor name="authentication"class="com.journaldev.struts2.interceptors.AuthenticationInterceptor"></interceptor><interceptor-stack name="authStack"><interceptor-ref name="authentication"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><default-interceptor-ref name="authStack"></default-interceptor-ref>
</package>

Note that defaultStack is already configured in struts-default package, that’s why we don’t need to define that in above example.

注意,defaultStack已經在struts-default包中配置了,這就是為什么我們不需要在上面的示例中定義它的原因。

Let’s create a simple application where we will use custom interceptor class to provide authentication for our application. Using interceptor will make our application loosely coupled, flexible and configurable. Our final project will look like below image.

讓我們創建一個簡單的應用程序,在這里我們將使用自定義攔截器類為我們的應用程序提供身份驗證。 使用攔截器將使我們的應用程序松散耦合,靈活且可配置。 我們的最終項目將如下圖所示。

Struts2攔截器示例項目配置文件 (Struts2 Interceptor Example Project configuration Files)

Java攔截器,web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xmlns="https://java.sun.com/xml/ns/javaee"xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>Struts2InterceptorExample</display-name><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>
</web-app>

pom.xml

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>Struts2InterceptorExample</groupId><artifactId>Struts2InterceptorExample</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><dependencies><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-core</artifactId><version>2.3.15.1</version></dependency></dependencies><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>2.3</version><configuration><warSourceDirectory>WebContent</warSourceDirectory><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins><finalName>${project.artifactId}</finalName></build>
</project>

pom.xml and web.xml configuration files are self understood.

攔截器使用、 pom.xml和web.xml配置文件是可以理解的。

struts.xml

struts.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""https://struts.apache.org/dtds/struts-2.3.dtd">
<struts><constant name="struts.convention.result.path" value="/"></constant><package name="user" namespace="/" extends="struts-default"><interceptors><interceptor name="authentication"class="com.journaldev.struts2.interceptors.AuthenticationInterceptor"></interceptor><interceptor-stack name="authStack"><interceptor-ref name="authentication"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><default-interceptor-ref name="authStack"></default-interceptor-ref><global-results><result name="login" type="redirect">/home.action</result></global-results><action name="home"><interceptor-ref name="defaultStack"></interceptor-ref><result>/login.jsp</result></action><action name="login" class="com.journaldev.struts2.actions.LoginAction"><interceptor-ref name="defaultStack"></interceptor-ref><result name="success">/welcome.jsp</result><result name="input">/login.jsp</result></action><action name="welcome" class="com.journaldev.struts2.actions.WelcomeAction"><result name="success">/welcome.jsp</result></action></package></struts>

Notice that I am declaring an interceptor authentication which is referring to class com.journaldev.struts2.interceptors.AuthenticationInterceptor.

注意,我聲明了一個攔截器authentication ,該authentication是指類com.journaldev.struts2.interceptors.AuthenticationInterceptor

自定義攔截器?Also notice that authStack is the default interceptor-stack for the package. I am not using this stack for login.jsp because it’s used for login and at that time user will not have session to authenticate.

另請注意, authStack是該軟件包的默認攔截器堆棧。 我沒有將這個堆棧用于login.jsp,因為它用于登錄,并且那時用戶將沒有會話可以進行身份??驗證。

結果頁 (Result Pages)

login.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login"><s:textfield name="user" label="User Name"></s:textfield><s:textfield name="password" label="Password" type="password"></s:textfield><s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

welcome.jsp

抓包攔截、 welcome.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="userName"></s:property></h3>
</body>
</html>

JSP result pages are easy to understand and nothing related to interceptors.

JSP結果頁面易于理解,與攔截器無關。

型號類別 (Model Class)

User.java

User.java

package com.journaldev.struts2.models;public class User {private String user;private String password;private String userName;public String getUser() {return user;}public void setUser(String user) {this.user = user;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}}

tcp攔截?A simple java bean with properties that are used in result pages. We will use this java bean in action class to hold properties.

一個簡單的Java Bean,具有在結果頁中使用的屬性。 我們將在動作類中使用此java bean來保存屬性。

定制攔截器 (Custom Interceptor)

UserAware.java

UserAware.java

package com.journaldev.struts2.interceptors;import com.journaldev.struts2.models.User;public interface UserAware {public void setUser(User user);
}

An interface similar to Struts 2 API *Aware interface, we will use it in our custom interceptor to inject values in action class. To learn more about Struts 2 API *Aware interface, please read:

java攔截器和過濾器的區別、 與Struts 2 API * Aware接口類似的接口,我們將在自定義攔截器中使用它來將值注入操作類。 要了解有關Struts 2 API * Aware接口的更多信息,請閱讀:

How to get Servlet Session, Request, Response, Context Attributes in Struts 2 Action

如何在Struts 2操作中獲取Servlet會話,請求,響應,上下文屬性

AuthenticationInterceptor.java

AuthenticationInterceptor.java

package com.journaldev.struts2.interceptors;import java.util.Map;import com.journaldev.struts2.models.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;public class AuthenticationInterceptor implements Interceptor {private static final long serialVersionUID = -5011962009065225959L;@Overridepublic void destroy() {//release resources here}@Overridepublic void init() {// create resources here}@Overridepublic String intercept(ActionInvocation actionInvocation)throws Exception {System.out.println("inside auth interceptor");Map<String, Object> sessionAttributes = actionInvocation.getInvocationContext().getSession();User user = (User) sessionAttributes.get("USER");if(user == null){return Action.LOGIN;}else{Action action = (Action) actionInvocation.getAction();if(action instanceof UserAware){((UserAware) action).setUser(user);}return actionInvocation.invoke();}}}

攔截和修改tcp數據、This is our custom interceptor class that is implementing com.opensymphony.xwork2.interceptor.Interceptor interface. init() and destroy() are interceptor lifecycle methods that we can implement to initialize and destroy some resources used in interceptor intercept() method.

這是實現com.opensymphony.xwork2.interceptor.Interceptor接口的自定義攔截器類。 init()和destroy()是攔截器生命周期方法,我們可以實現這些方法來初始化和銷毀??攔截器intercept()方法中使用的某些資源。

intercept() is the method invoked by ActionInvocation class, so this is where our interceptor code goes. We can get session attributes from ActionInvocation reference and use it to make sure session is valid. If we don’t find the attribute, we are returning global result “login” that will redirect user to login page. If session is valid, then we are injecting user into action class. instanceof keyword is used to make sure that action class is implementing UserAware interface. Finally we are calling ActionInvocation invoke() method that will call the next interceptor or action class in the chain.

Intercept()是ActionInvocation類調用的方法,因此這就是我們的攔截器代碼所在的位置。 我們可以從ActionInvocation參考獲取會話屬性,并使用它來確保會話有效。 如果找不到該屬性,則將返回全局結果“登錄”,該結果會將用戶重定向到登錄頁面。 如果會話有效,那么我們會將用戶注入到動作類中。 instanceof關鍵字用于確保操作類正在實現UserAware接口。 最后,我們調用ActionInvocation invoke()方法,該方法將調用鏈中的下一個攔截器或操作類。

動作班 (Action Classes)

LoginAction.java

LoginAction.java

package com.journaldev.struts2.actions;import java.util.Map;import org.apache.struts2.interceptor.SessionAware;import com.journaldev.struts2.models.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;public class LoginAction extends ActionSupport implements SessionAware, ModelDriven<User>{private static final long serialVersionUID = -3369875299120377549L;@Overridepublic String execute(){System.out.println("inside execute");if("pankaj".equals(user.getUser()) && "admin".equals(user.getPassword())){user.setUserName("Pankaj Kumar");sessionAttributes.put("USER", user);return SUCCESS;}return INPUT;}private User user = new User();private Map<String, Object> sessionAttributes = null;@Overridepublic void setSession(Map<String, Object> sessionAttributes) {this.sessionAttributes = sessionAttributes;}@Overridepublic User getModel() {return user;}}

Notice that LoginAction is implementing SessionAware interface to get session attributes and if user is validated, then putting user attribute in session to be used in authentication interceptor for validation. Notice that LoginAction is not implementing UserAware interface.

請注意,LoginAction正在實現SessionAware接口以獲取會話屬性,并且如果驗證了用戶,則將用戶屬性放在會話中以在身份驗證攔截器中用于驗證。 請注意,LoginAction沒有實現UserAware接口。

WelcomeAction.java

WelcomeAction.java

package com.journaldev.struts2.actions;import com.journaldev.struts2.interceptors.UserAware;
import com.journaldev.struts2.models.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;public class WelcomeAction extends ActionSupport implements UserAware, ModelDriven<User> {private static final long serialVersionUID = 8111120314704779336L;@Overridepublic String execute(){return SUCCESS;}private User user;@Overridepublic void setUser(User user) {this.user=user;}public User getUser(User user){return this.user;}@Overridepublic User getModel() {return this.user;}}

Notice that WelcomeAction is implementing UserAware interface and our AuthenticationInterceptor is injecting it to the action class behind the scene. Notice that action class is simple and there is no code for validating the user session or to set the user bean.

注意,WelcomeAction正在實現UserAware接口,我們的AuthenticationInterceptor將其注入到幕后的action類中。 請注意,動作類很簡單,沒有用于驗證用戶會話或設置用戶Bean的代碼。

From above action classes code, it’s clear that if we use interceptors smartly, we can reduce a lot of code redundancy for common tasks that we need to do for multiple actions.

從上面的動作類代碼中可以清楚地看出,如果我們聰明地使用攔截器,我們可以減少執行多個動作所需的常見任務的大量代碼冗余。

When we execute above project, we get following response pages.

當我們執行以上項目時,我們得到以下響應頁面。

If you are not logged in and you will try to invoke login.action, our authentication interceptor will forward you to login page and action class will never be invoked.

如果您尚未登錄,并且嘗試調用login.action,則我們的身份驗證攔截器會將您轉發到登錄頁面,并且永遠不會調用action類。

Download Struts2 Interceptor Example Project下載Struts2攔截器示例項目

That’s all for Struts 2 interceptors tutorial, it’s one of the important features of Struts 2 and you should try to use it for reusability.

這就是Struts 2攔截器教程的全部內容,這是Struts 2的重要功能之一,您應該嘗試將其用于可重用性。

翻譯自: https://www.journaldev.com/2210/struts-2-interceptor-example

struts2 攔截器

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/183273.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息