一、Struts2拦截器概述
- 拦截器(Interceptor是 Struts2.0的核心组成部分;
- Struts2拦截器在访问某个Action方法之前或之后实施拦截;
- Struts2拦截器是可插拔的,其是拦截器是AOP(面向切面编程)思想的一种实现;
- Struts2的很多功能都是构建在拦截器基础之上的,如类型转换、国际化、输入验证、文件的上传与下载等;
- 拦截器栈(Interceptor Stack):将拦截器按一定的顺序联结成一条链,在访问被拦截的方法时, Struts2拦截器链中的拦截器会按其定义顺序被依次调用。
二、Struts2自带拦截器
三、Interceptor接口
public interface Interceptor extends Serializable {
/**
* 该方法将在拦截器被创建后立即被调用,在拦截器的生命周期内只被调用一次;
* 功能:可以在该方法中对相关资源进行必要的初始化。
*/
void init();
/**
* 每拦截一个请求,该方法就会被调用一次。
*/
String intercept(ActionInvocation invocation) throws Exception;
/**
* 该方法将在拦截器被销毁之前调用,在拦截器的生命周期内也只被调用一次。
*/
void destroy();
}
具体说明如下:
- 每个拦截器都是实现了com.opensymphony.xwork2.interceptor.Interceptor接口的Java类;
- Struts会依次调用为某个Action而注册的每一个拦截器的interecept()方法;
- 每次调用interecept()方法,Struts均会传递一个ActionInvocation接口的实例;
- ActionInvocation接口代表一个给定Action的执行状态,拦截器可以从该类的对象中获得与该Action相关的Action对象和Result对象;
- 在完成拦截器自己的任务之后,拦截器将调用ActionInvocation对象的invoke()方法前进到Action处理流程的下一个环节;
- AbstractInterceptor类实现了Interceptor接口,并为init()方法和destroy()方法提供了空白实现。
四、自定义拦截器
4.1 自定义拦截器类
可以直接实现Interceptor接口或选择继承于AbstractInterceptor抽象类。核心示例代码如下:
package com.qiaobc.struts.interceptors;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class MyInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("before invocation.invoke() ...");
String result = invocation.invoke();
System.out.println("after invocation.invoke() ...");
return result;
}
}
4.2 配置自定义拦截器类
可以在struts.xml文件中配置自定义的拦截器类,核心配置代码如下:
<interceptors>
<interceptor name="test" class="com.qiaobc.struts.interceptors.MyInterceptor"></interceptor>
</interceptors>
<action name="testToken" class="com.qiaobc.struts.token.TokenAction">
<interceptor-ref name="test"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/success.jsp</result>
<result name="invalid.token">/token-error.jsp</result>
</action>
注意:在自定义拦截器中可以选择不调用ActionInvocation的invoke()方法,则后续拦截器和Action方法将不会被调用;同时,Struts会渲染自定义拦截器intercept()方法返回值所对应的result。