Struts2 自定义拦截器

所有的拦截器都需要实现Interceptor接口或者继承Interceptor接口的扩展实现类
    
    * 要重写init()、intercept()、destroy()方法
    
        * init()是在struts2框架运行时执行,在拦截器的生命周期中只执行一次,可以做必要的内容的初始化工作
        
        * intercept(),是每一次请求就执行一次,做相关处理工作。
        
            * intercept()方法接收一个ActionInvocation接口的实例
            
            * 通过这个接口的实例,可以获取以下内容

  * destroy()是在拦截器销毁前执行,在拦截器的声明周期中只执行一次

 1 package cn.test.aop;
 2 
 3 import com.opensymphony.xwork2.ActionInvocation;
 4 import com.opensymphony.xwork2.interceptor.Interceptor;
 5 
 6 public class ExpresionInterception implements Interceptor {
 7     public void init() {
 8     }
 9 
10     public String intercept(ActionInvocation Invo) throws Exception {
11         //   cn.test.aop.UserAction@31cc903c    动作类的对象
12         System.err.println(Invo.getAction());        
13         //     cn.test.aop.UserAction@31cc903c    与invocation.getAction()方法获取的是同一的对象
14         System.err.println(Invo.getProxy().getAction());
15         //    UserAction_Save   自定义配置文件中的action标签的name属性的值
16         System.err.println(Invo.getProxy().getActionName());
17         //   save   对应动作类指定要执行的方法名
18         System.err.println(Invo.getProxy().getMethod());
19         //    /aop   命名空间  自定义配置文件中的package标签的namespace属性的值
20         System.err.println(Invo.getProxy().getNamespace());
21         //null   返回结果
22         System.err.println(Invo.getResult());
23         
24         
25         return null;
26     }
27     public void destroy() {
28     }
29 
30 }

 

* 在struts.xml配置文件中,进行注册

   在配置文件中的package标签下,进行相关配置

 1 <!-- 声明自定义拦截器 -->
 2     <interceptors>
 3         <interceptor name="ExpresionInterception" class="cn.test.aop.ExpresionInterception"></interceptor>
 4         <!-- 声明自定义拦截器栈 -->
 5         <interceptor-stack name="expInterception">
 6             <interceptor-ref name="defaultStack"></interceptor-ref>
 7             <!-- 配置使用自定义拦截器 -->
 8             <interceptor-ref name="ExpresionInterception"></interceptor-ref>
 9         </interceptor-stack>
10     </interceptors>
11     <!-- 修改struts2框架运行时,执行自定义拦截器 -->
12     <default-interceptor-ref name="ExpresionInterception"></default-interceptor-ref>
13     

 

原文地址:https://www.cnblogs.com/liuwt365/p/4208224.html