Struts2的拦截器可以应用在action范围内也可以用在package范围内:
第一种、action范围内:
<action name="register" class="org.apache.struts.register.action.Register" method="execute">
<interceptor-ref name="timer" />
<interceptor-ref name="logger" />
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
</interceptor-ref>
<result name="success">thankyou.jsp</result>
<result name="input">register.jsp</result>
</action>
第二种、package范围:
<package name="basicstruts2" extends="struts-default" >
<interceptors>
<interceptor-stack name="appDefault">
<interceptor-ref name="timer" />
<interceptor-ref name="logger" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="appDefault" />
<!-- rest of package omitted -->
</package>
但是需要注意的一点是:
Note that in both examples we are still executing all the other interceptors by including the defaultStack as one of the interceptor-ref nodes. When you specify what interceptors you want to use for an Action or a package then only those interceptors are executed. So if in the example we had left out the interceptor-ref for defaultStack only the logger and timer interceptors would have executed.
拦截器可以是Struts2自带的也可以是自己编写的:
第一种、例子中的timer、logger、defaultStack都是Struts2框架自带的;
第二种、自己编写interceptor:
a、编写一个interceptor:
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class SimpleInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
MyAction action = (MyAction)invocation.getAction();
action.setDate(new Date());
return invocation.invoke();
}
}
b、配置应用这个interceptor:
<struts>
...
<package name="struts-default">
<interceptors>
<interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
<interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
...
</interceptors>
</package>
...
</struts>
OK了!