一、編寫攔截器
1、 實現(xiàn)接口com.opensymphony.xwork2.Intercepter(或繼承com.opensymphony.xwork2.AbstractInterceptor)
2、 在interceptor方法中加入如下代碼:
public String intercept(ActionInvocation arg0) throws Exception {
System.out.println("Before"); //在Action之前調(diào)用
String result = arg0.invoke(); //如果此攔截器之后還有攔截器,則調(diào)用下個攔截器的intercept方法
//如果之后沒有了攔截器,則調(diào)用Action的execute方法
System.out.println("After");
return result;
}
二、在Struts.xml中配置攔截器
1、 在struts.xml中聲明攔截器和攔截器Stack,攔截器Stack可以包括多個攔截器和其他Stack。
<interceptors>
<!-- 攔截器 -->
<interceptor name="MyInterceptor" class="com.test.interceptor.MyInterceptor"></interceptor>
<!-- 攔截器Stack -->
<interceptor-stack name="validationWorkflowStack">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/>
</interceptor-stack>
</interceptors>
2、 將攔截器配置到單個Action中,只攔截此Action中的execute方法。
<action name="register" class="com.test.action.RegisterAction" method="test">
<result name="success">/success.jsp</result>
<result name="input">/register2.jsp</result>
<interceptor-ref name="MyInterceptor"></interceptor-ref>
</action>
3、 將攔截器配置到所有Action中,攔截所有Action中的execute方法。
<default-interceptor-ref name="MyInterceptor"></default-interceptor-ref>
對已經(jīng)單獨配置了攔截器的Action不起作用
三、攔截Action中指定的方法
1、 繼承com.opensymphony.xwork2.interceptor.MethodFilterInterceptor。
2、 因為是針對某個Action的方法,所以只能配置在Action內(nèi)部
<action name="register" class="com.test.action.RegisterAction" method="test">
<result name="success">/success.jsp</result>
<result name="input">/register2.jsp</result>
<interceptor-ref name="MyInterceptor">
<param name="includeMethod">test,execute</param> <!-- 攔截text和execute方法,方法間用逗號分隔 -->
<param name="excludeMethod">myfun</param> <!-- 不攔截myfun方法 -->
</interceptor-ref>
</action>
四、struts2攔截器的interceptor方法中,參數(shù)ActionInvocation可用來獲取頁面用戶輸入的信息。
public String intercept(ActionInvocation arg0) throws Exception {
Map map = arg0.getInvocationContext().getSession();
if(map.get("user") == null) {
return Action.LOGIN;
} else {
return arg0.invoke();
}
}