0.拦截器的作用
用于在Action执行之前或者执行之后,进行拦截,并加入我们自定义的代码,执行相关的操作,是实现AOP的一种策略。
1拦截器在Action之前还是之后执行
主要看invocation.invoke();的位置,在此函数之前的代码为Action代码执行前拦截器会做的,反之,之后的的代码即为Action之后拦截器做的。
后置拦截器示例
package ...interceptor;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class UserInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
invocation.invoke();
//
Action执行之后执行的代码...
//
}
}
前置拦截器示例
package ...interceptor;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class UserInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
//
Action执行之前执行的代码...
//
<pre name="code" class="java"><span style="white-space:pre"> </span>invocation.invoke();
}}
2拦截器的三种实现方式
2.1实现Interceptor接口
需要实现三个方法:init,destroy,intercept
2.2继承AbstractInterceptor类
实现intercept(ActionInvocation invocation)方法即可
2.3
继承MethodFilterInterceptor类
重写doIntercept()方法
3.基础知识
3.1默认拦截器是在每个Action都会执行拦截的
如:<default-interceptor-ref name="默认拦截器名称"/>
3.2要想只对某个Action拦截的话,可以将该拦截器设置为该Action的拦截器
如:
<action name="login" class="...Login">
<result name="success" type="redirect">patientList.action</result>
<result name="error">/login.jsp</result>
<interceptor-ref name="userInterceptorStack"/>
</action>
3.3上述拦截器可能带来的问题
struts2默认的拦截器功能丢失,因为这样配置之后,就只会执行用户配置的这个拦截器了,解决办法就是加入struts2的默认拦截器
如:
<action name="login" class="...Login">
<result name="success" type="redirect">patientList.action</result>
<result name="error">/login.jsp</result>
<interceptor-ref name="userInterceptorStack"/>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>