|
一、編寫(xiě)攔截器
1、 實(shí)現(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)用下個(gè)攔截器的intercept方法 //如果之后沒(méi)有了攔截器,則調(diào)用Action的execute方法 System.out.println("After"); return result; } 二、在Struts.xml中配置攔截器
1、 在struts.xml中聲明攔截器和攔截器Stack,攔截器Stack可以包括多個(gè)攔截器和其他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、 將攔截器配置到單個(gè)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>
對(duì)已經(jīng)單獨(dú)配置了攔截器的Action不起作用
三、攔截Action中指定的方法
1、 繼承com.opensymphony.xwork2.interceptor.MethodFilterInterceptor。 2、 因?yàn)槭轻槍?duì)某個(gè)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方法,方法間用逗號(hào)分隔 -->
<param name="excludeMethod">myfun</param> <!-- 不攔截myfun方法 --> </interceptor-ref> </action>
四、struts2攔截器的interceptor方法中,參數(shù)ActionInvocation可用來(lái)獲取頁(yè)面用戶(hù)輸入的信息。
public String intercept(ActionInvocation arg0) throws Exception { Map map = arg0.getInvocationContext().getSession();
if(map.get("user") == null) {
return Action.LOGIN;
} else {
return arg0.invoke();
}
}
本文來(lái)自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/sendfeng/archive/2009/06/07/4248120.aspx |
|
|