10、自定义拦截器

1、Struts2 拦截器

  • 拦截器(Interceptor)是 Struts 2 的核心组成部分。
  • Struts2 很多功能都是构建在拦截器基础之上的,例如文件的上传和下载、国际化、数据类型转换和数据校验等等。
  • Struts2 拦截器在访问某个 Action 方法之前或之后实施拦截
  • Struts2 拦截器是可插拔的, 拦截器是 AOP(面向切面编程) 的一种实现.
    拦截器栈(Interceptor Stack): 将拦截器按一定的顺序联结成一条链. 在访问被拦截的方法时, Struts2 拦截器链中的拦截器就会按其之前定义的顺序被依次调用
    • 从拦截器进去,再从拦截器出来

2、 Struts2自带的拦截器

3、Interceptor 接口

  • 每个拦截器都是实现了 com.opensymphony.xwork2.interceptor.Interceptor 接口的 Java 类:
public interface Interceptor extends Serializable {
 
    void destroy();
    void init();
    String intercept(ActionInvocation invocation) throws Exception;
 
}
  • init: 该方法将在拦截器被创建后立即被调用, 它在拦截器的生命周期内只被调用一次. 可以在该方法中对相关资源进行必要的初始化
  • interecept: 每拦截一个请求, 该方法就会被调用一次.
  • destroy: 该方法将在拦截器被销毁之前被调用, 它在拦截器的生命周期内也只被调用一次.
  • Struts 会依次调用为某个 Action 而注册的每一个拦截器的 interecept 方法.
  • 每次调用 interecept 方法时, Struts 会传递一个 ActionInvocation 接口的实例.
  • ActionInvocation: 代表一个给定 Action 的执行状态, 拦截器可以从该类的对象里获得与该 Action 相关联的 Action 对象和 Result 对象. 在完成拦截器自己的任务之后, 拦截器将调用 ActionInvocation 对象的 invoke 方法前进到 Action 处理流程的下一个环节.
  • AbstractInterceptor 实现了 Interceptor 接口. 并为 init, destroy 提供了一个空白的实现

4、自定义拦截器

  • 定义自定义拦截器的步骤

    • 自定义拦截器
    • 在 struts.xml 文件中配置自定义的拦截器
  • 示例代码:

  • 自定义拦截器

public class MyInterceptor extends AbstractInterceptor{

    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("before invocation.invoke...");

        String result = invocation.invoke();
        System.out.println("after invocation.invoke...");
        return result;
        //return "success"; 直接返回一个值,将不会调用后面的拦截器
    }

}
  • 在struts.xml配置文件中注册拦截器-在package标签中注册拦截器
 <interceptors>
   <!-- 配置拦截器 -->
   <interceptor name="myInterceptor" class="org.pan.struts.interceptor.MyInterceptor"/>
   <interceptor-stack name="myIntercepterStack">
       <interceptor-ref name="paramsPrepareParamsStack"/>
   </interceptor-stack>
</interceptors>
  • 使用拦截器: 在action中使用拦截器
    • 注意:如果在action中引用了自定义拦截器,那么还需要在引入默认的拦截器栈,
    • 如果不引用则整个Action只会经过自定义拦截器,而不会在调用其他的拦截器,
    • 通过interceptor-ref来决定拦截器的执行位置越靠前则越先执行
<action name="user_*" class="org.pan.struts.action.TestValidationAction" method="{1}">
    <!--使用拦截器 -->
    <interceptor-ref name="myInterceptor"/>
    <!-- 还需要引用拦截器器栈 -->
    <interceptor-ref name="myIntercepterStack"/>

    <result name="success">/WEB-INF/views/success.jsp</result>
    <result name="{1}">/WEB-INF/views/{1}.jsp</result>
    <result name="input">/WEB-INF/views/input.jsp</result>
</action>
人生如棋,我愿为为卒;行走虽慢,可曾见我后退一步!
原文地址:https://www.cnblogs.com/MPPC/p/6130599.html