Struts2 自定义拦截器

本文介绍如何在Struts2框架中实现自定义拦截器,包括实现Interceptor接口的init(), intercept(), destroy()方法,以及在struts.xml配置文件中的注册方式。

所有的拦截器都需要实现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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值