拦截器接口
自行编写的拦截器,必须实现com.opensymphony.xwork2.interceptor.Interceptor 接口。
Interceptor.java
public interface Inteceptor extends Serializable{
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception();
}
init方法在拦截器被实例化之后、调用intercept之前被调用。这是分配任何会被拦截器所使用资源的地方。
intercept方法是拦截器代码被书写的地方。就像一个动作方法,intercept返回一个被Struts用来转发请求到另一个网页资源的结果。使用类型为ActionInvocation的参数调用invoke ,会执行这个动作(如果这是栈之中的最后一个拦截器),或者调用另一个拦截器。
记住,invoke会在结果已经被调用之后返回(例如在你的JSP已经被渲染之后),让类似打开对话框之类的事情变得完美。如果你希望在结果被调用之前就做点什么,淫荡实现一个PreResultListener。
重写destroy,在应用停止时释放资源。
线程安全
拦截器必须是线程安全的!
一个Struts2 动作实例为每个请求都创建,并且不需要是线程安全的。相反地,拦截器是在请求之间共享的,因而必须是线程安全的。
AbstractInterceptor 抽象拦截器
AbstractInterceptor类提供了一个init和destroy空的实现,并且如果这些方法不被实现,也可以被使用。
映射
通过在interceptors元素中嵌套使用interceptor元素来声明拦截器。下面是来自struts-default.xml。
<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"/>
···
</struts>
示例
假设现有一个类型为”MyAction”的动作,有一个setDate(Date)方法;这里简单的拦截器会设置动作的date为当前时间:
拦截器示例
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();
}
}