Struts2拦截器

Struts2的拦截器和Servlet过滤器类似。在执行Action的execute方法之前,Struts2会首先执行在struts.xml中引用的拦截器,在执行完所有的intercept方法后,会执行Action的execute方法。
Struts2拦截器类必须从com.opensymphony.xwork2.interceptor.Interceptor接口继承,在Intercepter接口中有如下三个方法需要实现:
void destroy();
void init();
String intercept(ActionInvocation invocation)throws Exception;
其中intercept()方法时拦截器的核心方法,所有安装的拦截器都会调用这个方法,在Struts2中已经在struts-default.xml中预定义了一些自带的拦截器,如timer、params等。如果在标签中继承struts-default,则当前package就会自动拥有struts-default.xml中的所有配置。代码如下:
...

一个拦截器就是一个普通的类,只是这个类必须实现com.oprnsymphony.xwork2.interceptor.Interceptor接口,接口有如下三个方法:
public interface Interceptor extends Serializable{
    void destory();
    void init();
    String intercept(ActionInvocation invocation)throws Exception;
}
其中init和destroy方法只在拦截器加载和释放(都由Struts2自身处理)时执行一次。而intercept方法在每次访问动作时都会被调用。Struts2在调用拦截器时,每个拦截器类只有一个对象实例,而所有引用这个拦截器的动作都共享这一个拦截器类的对象实例,因此,在实现Interceptor接口的类中如果使用变量,要注意同步问题。

拦截器通过请求参数action指定一个拦截器类中的方法,并调用这个方法(我们可以使用这个拦截器对某一特定的动作进行预处理)。如果方法不存在,或是action参数不存在,则继续执行下面的代码。如下面的URL:
http://localhost:8080/struts2/test/interceptor.action?action=test
访问上面的URL后,拦截器就会调用拦截器中test()方法,如果这个方法不存在,则调用invocation.invoke方法,invoke方法和Servlet过滤器中调用FilterChain.doFilter()方法类似,如果在当前拦截器后面还有其他的拦截器,则invoke方法就是调用后面拦截器的intercept方法,否则,invoke会调用Action类的execute方法(或其他的执行方法)。

你可能感兴趣的:(Struts2拦截器)