Struts2攔截器的自定義實現
阿新 • • 發佈:2018-12-21
為了實現自定義攔截器,Struts2提供了Interceptor介面,以及對該介面實現的一個抽象攔截器類(AbstractInterceptor)。實現攔截器類一般可以實現Interceptor介面,或者直接繼承AbstractInterceptor類。Struts2還提供了一個MethodFilterInterceptor類,該類是AbstractInterceptor類的子類,若要實現方法過濾,就需要繼承MethodFilterInterceptor,設計方法攔截器。
使用者定義一個攔截器一般需要一下3個步驟:
- 自定義一個實現Interceptor介面(或繼承AbstractInterceptor或繼承MethodFilterInterceptor)的類。
- 在struts.xml中註冊上一步中定義的攔截器。
- 在需要使用的Action中引用上述定義的攔截器。
先寫一個input.jsp頁面,讓它跳轉到Action中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a href="Action1.action">請點選跳轉</a> </body> </html>
Action.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
public class Action1 extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("Action1執行了");
return SUCCESS;
}
}
再寫個要跳轉到的jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% // System.out.println("攔截器01執行了"); %> </body> </html>
還有攔截器,我用的是繼承AbstractInterceptor類。
攔截器1.java
package interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class interceptor1 extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("攔截器1執行了...");
String Obj = invocation.invoke();
System.out.println("攔截器1執行結束了...");
return Obj;
}
}
攔截器2.jsp
package interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class interceptor2 extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("攔截器2執行了...");
String Obj = invocation.invoke();
System.out.println("攔截器2執行結束了...");
return Obj;
}
}
然後還要配置struts.xml檔案
<package name="default" namespace="/" extends="struts-default">
<!-- 定義攔截器 -->
<interceptors>
<interceptor name="interceptor1" class="interceptor.interceptor1">
</interceptor>
<interceptor name="interceptor2" class="interceptor.interceptor2">
</interceptor>
<!-- 定義攔截器棧 -->
<!-- 引入攔截器(一旦引入自定義的攔截器,預設攔截器棧的攔截器就不執行了) -->
<interceptor-stack name="myStack">
<!-- 引入預設攔截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引入自定義攔截器 -->
<interceptor-ref name="interceptor1"></interceptor-ref>
<interceptor-ref name="interceptor2"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="Action1" class="Action.Action1">
<result>/攔截器01.jsp</result>
<interceptor-ref name="myStack"></interceptor-ref>
</action>
</package>
執行結果: