【前言】
拦截器(interceptor)是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。通常Struts的功能中有AOP作用,其中拦截器是实现AOP的一种策略。
【内容】
1.编写实现interceptor接口类:接口类中destroy和init方法并不重要,重要的是intercept方法,其中ActionInvocation参数的invoke调用方法是告诉Struts接下来要做的事情。
public class TheInterceptor1 implements Interceptor {
public void destroy() {
// TODO Auto-generated method stub
}
public void init() {
//服务器启动的时候运用拦截器 !
System.out.println("init invoked!");
}
public String intercept(ActionInvocation arg0) throws Exception {
System.out.println("before");
System.out.println(arg0.getClass());
String result=arg0.invoke();
System.out.println("after");
return result;
}
}
2.Struts.xml中配置定义的拦截器
<package name="struts2" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="theInterceptor1" class="com.cyl.interceptor.TheInterceptor1"></interceptor>
</interceptors>
</package>
</struts>
3.在action中使用拦截器
<action name="token" class="com.cyl.struts2.TokenAction">
<result name="success">/tokenSuccess.jsp</result>
<result name="input">/token.jsp</result>
<interceptor-ref name="theInterceptor1"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
注:
一旦定义了自己的拦截器,要将其配置到action之后,在action的最后要添加上默认拦截器栈:defaultStack,否则默认的拦截器就会不起作用。Struts的默认拦截器参考:http://blog.csdn.net/getchance/article/details/7982251
【总结】
拦截器(interceptor)是Struts2最强大的特性之一,也可以说是struts2的核心,拦截器可以让你在Action和result被执行之前或之后进行一些处理。其实拦截器和之前学的filter(过滤器)非常的像,但是有一些区别,将在后面的文章做简单介绍!