Struts2 拦截器
- 拦截器是在访问某个方法,字段之前或之后实施拦截。Struts2的核心功能通过拦截器来实现。
- 拦截器是AOP的一种实现
- 拦截器栈
-拦截器栈是讲拦截器按照一定的顺序联结成一条链。
-在访问被拦截的方法或字段时,拦截器链中的拦截器就会按照其之前定义的顺序被调用 - 实现原理
-请求Struts2的action时,Struts2会查找配置文件,并根据其配置实例化相应的拦截器对象,然后串成一个列表,最后一个一个地调用列表中的拦截器 - 拦截器的作用:对于action的一些公共处理代码,可以放到拦截器中来实现。如:权限控制,日志
拦截器和过滤器的区别:
1、拦截器和过滤器概念很相似
2、过滤器隶属于web容器,可以过滤一切请求(action、servlet、jsp、html等等)拦截器隶属于struts2框架,只能拦截action(无法拦截对jsp的请求)
3、过滤器内部采用函数回调来实现,拦截器采用动态代理来实现
拦截器的实现步骤:
1、编写拦截器(实现interceptor接口或者继承Abstractinterceptor类)
package cn.xm.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TimeInterceptor implements Interceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
long start = System.currentTimeMillis();
// 执行下一个拦截器,当拦截器执行完后执行action
String result = invocation.invoke();
long end = System.currentTimeMillis();
System.out.println("执行该action使用的时间为" + (end - start) + "ms");
return result;
}
}
2、在struts2.xml中配置拦截器 、在action中引用拦截器
<package name="default" namespace="/" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="time" class="cn.xm.interceptor.TimeInterceptor"></interceptor>
</interceptors>
<action name="Hello" class="cn.xm.action.HelloAction">
<result name = "success">show.jsp</result>
<!-- 引用拦截器 -->
<interceptor-ref name="time"></interceptor-ref>
</action>
</package>
3、执行效果如图