struts2 4
拦截器
- 用于在某个方法或字典被访问之前或者之后进行拦截,是AOP的一种实现策略
- 拦截器是动态拦截action调用的对象
实现原理
- 大部分时候,拦截器通过代理的方式来调用,当请求到达struts2的ServletDispatcher时,struts2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表,最后一个一个地调用列表中的拦截器
struts2执行流程
自定义拦截器
- 需要直接或间界的实现com.opensymphony.xwork2.interceptor.Interceptor
// public interface Interceptor extends Serializable{ //在拦截器被创建后立即被调用,在拦截器生命周期内只被调用 void init(); //在拦截器销毁时调用,用来释放所有相关资源 void destroy(); //核心方法,用来添加真正执行拦截工作的代码,返回一个字符串作为逻辑视图,系统根据字符串跳转到对应的视图资源 String intercept(ActionInvocation invocation) throw Exception; }
- 继承抽象拦截器类AbstractIntercepter,该类实现了Interceptor接口,并且提供init方法和destroy方法的空实现
public abstract class AbstractInterceptor implements Interceptor{ public void init(){} public void destroy(){} public abstract String intercept(ActionInvocation invocation) throws Exception; }
拦截器的配置
- 拦截器的配置是在struts.xml文件中完成的
- name指定拦截器的名称
- class指定拦截器的实现类
- param标签用于给拦截器传入参数
<interceptor name="interceptorName" class="interceptorClass"> <params name="paramName">paramValue</param> </interceptor>
- 拦截器栈:把多拦截器组成一个拦截器栈,使用时将多个拦截器作为一个整体来用,当拦截器被附加到一个Action上时,在执行Action之前必须先执行拦截器栈中的每一个拦截器
<interceptors> //配置拦截器栈的名称 <interceptor-stack name="interceptorStackName"> <interceptor-ref name="interceptorName" /> ... </interceptor-stack> </interceptors>
//在一个拦截器内包含另一个拦截器 <package name="default" namespace="/" extends="struts-default"> //声明拦截器 <interceptors> <interceptor name="interceptor1" class="interceptorClass" /> <interceptor name="interceptor2" class="interceptorClass" /> //定义一个拦截器栈,包含两个拦截器和一个拦截器栈 <interceptor-stack name="mystack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="interceptor1"/> <interceptor-ref name="interceptor2"/> </interceptor-stack> </interceptors> </package>