说明
今天看书看到拦截器,觉得挺有意思的,记录一下
拦截器
拦截器(Interceptor)是Struts2框架的核心组成部分。拦截器是动态拦截Action调用的对象。它提供一种机制,使开发者可以在一个Action前后执行需要的代码,可以在一个Action执行前阻止其执行,也可以在Action执行后做一些相应的工作。Struts2拦截器是可插拔的,拦截器是AOP的一种实现。
配置与使用
拦截器是定义在struts.xml配置文件中的,格式是:
<interceptor name=“拦截器名字” class=“拦截器对应的java类”/ >
例如,在user包下定义一个名为myinterceptor的拦截器
<package name="user" extends="struts-default" />
<interceptors>
<interceptor name="myinterceptor" class="com.shanmu.interceptor.MyInterceptor"/>
</interceptors>
</package>
也可以定义一个拦截器栈,拦截器栈中包含多个拦截器,使用一个拦截器栈等于使用多个拦截器,语法格式为:
< interceptors >
< interceptor-stack name=“拦截器栈名字” >
< interceptor-ref name=“拦截器名字” />
< /interceptor-stack>
< /interceptors>
例如,定义一个拦截器栈,在里面定义三个拦截器
<interceptors>
<!-- 定义mystack拦截器栈 -->
<interceptor-stack name="mystack">
<!-- 引用Struts2系统拦截器token -->
<interceptor-ref name="token"/>
<!-- 引用Struts2系统拦截器timer -->
<interceptor-ref name="timer"/>
<!-- 引用自定义拦截器myinterceptor,若有参数可以用param指定 -->
<interceptor-ref name="myinterceptor"/>
</interceptor-stack>
</interceptors>
使用拦截器
语法格式是:
< intercept-ref name=“拦截器名”/>
使用拦截器要在struts.xml中配置,例
<struts>
<package name="user" extends="struts-default" />
<interceptors>
<!-- 定义了两个拦截器,分别为mi1,mi2 -->
<interceptor name="mi1" class="com.shanmu.interceptor.MyInterceptor1"/>
<interceptor name="mi2" class="com.shanmu.interceptor.MyInterceptor2"/>
<!-- 定义mystack拦截器栈 -->
<interceptor-stack name="mystack">
<interceptor-ref name="token"/>
<interceptor-ref name="myinterceptor"/>
</interceptor-stack>
</interceptors>
<!-- 配置UserAction类 -->
<action name="user" class="com.shanmu.action.UserAction">
<result name="success">success.jsp</result>
<result name="input">login.jsp</result>
<!-- 使用mi1拦截器 -->
<interceptor-ref name="mi1"/>
<!-- 使用mi2拦截器 -->
<interceptor-ref name="mi2"/>
<!-- 使用默认拦截器 -->
<interceptor-ref name="defaultStack"/>
</action>
<!-- 配置ProductAction类 -->
<action name="product" class="com.shanmu.action.ProductAction">
<!-- 使用拦截器栈拦截 -->
<interceptor-ref name="mystack"/>
<result>/success.jsp</result>
</action>
</package>
</struts>
配置默认拦截器
一般Struts2中都是把defaultStack作为系统默认拦截器,我们也可以将自己定义的拦截器定义为默认拦截器,例如把刚才自定义的mi1作为默认拦截器,只需在package标签中加上下面的语句:
<default-interceptor-ref name="mi1"/>
自定义拦截器类
自定义拦截器类需要实现com.opensymphony.xwork2.interceptor.Interceptor接口或者继承该接口的实现类AbstractInterceptor。
Interceptor接口的定义如下:
public abstract interface Interceptor extends Serializable{
public abstract void destory();
//用于在拦截器执行之后销毁资源,在垃圾回收前调用
public abstract void init();
//初始化系统资源,在拦截器执行前调用
public abstract String intercept(ActionInvocation paramActionInvocation)throws Exception;
//实现具体的拦截操作
}
AbstractInterceptor定义如下:
public abstract class AbstractInterceptor implements Interceptor{
public void init(){ }
public void destory(){ }
public abstract String intercept(ActionInvocation paramActionInvocation)throws Exception;
}
所以AbstractInterceptor实现了Interceptor接口,但是对init()和destory()方法进行空实现,我们只需要实现intercept()方法就可以了。
这里的ActionInvocation参数可以调用invoke方法,表示通过该拦截器。
最后
后面会写一个拦截器的小例子。