Struts2自定义拦截器

自定义拦截器的2种方法

1.实现(implemetns) interceptor接口,开发中一般不用,因为它要实现interceptor接口的3个方法void init(),void destroy(),String intercept(ActionInvocation invocation)throws Exception

2.继承(extends) AbstractInterceptor,只需要实现String intercept(ActionInvocation invocation)throws Exception方法即可,示例如下:

 1 package cn.bd.jboa.interceptor;
 2 
 3 import java.util.Map;
 4 
 5 import com.opensymphony.xwork2.ActionInvocation;
 6 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
 7 
 8 /**
 9  * 拦截器
10  * @author TaoXianXue
11  *
12  */
13 
14 public class LoginInterceptor extends AbstractInterceptor{
15 
16     /**
17      * 
18      */
19     private static final long serialVersionUID = 1L;
20     
21 
22     @Override
23     public String intercept(ActionInvocation invocation) throws Exception {
24         //获取用户会话信息
25         Map session=invocation.getInvocationContext().getSession();
26         //session.get("employee_name");//用户名
27         String sn=(String) session.get("employee_sn");//用户编号
28         if(sn==null || sn.equals("")){
29             return "login";//终止执行,返回登录页面
30         }else{
31             return invocation.invoke();//继续执行剩余的拦截器
32         }
33     }
34 
35 }

在struts.xml中的配置如下:

 1 <interceptors>
 2             <!-- 拦截器栈 -->
 3             <interceptor-stack name="loginStack">
 4                 <interceptor-ref name="loginAuthorization"></interceptor-ref>
 5                 <interceptor-ref name="defaultStack"></interceptor-ref><!-- 引用struts2默认的拦截器 -->
 6             </interceptor-stack>
 7             <!-- 定义权限验证拦截器 -->
 8             <interceptor name="loginAuthorization" class="cn.bd.jboa.interceptor.LoginInterceptor"></interceptor>
 9  </interceptors>
10         
11         
12         <!--自定义默认的拦截器 -->
13         <!-- <default-interceptor-ref name="loginStack"></default-interceptor-ref> -->
14 
15 
16 
17 <!--在action中引用自定义的拦截器 -->
18 <action name="claimVoucher_*" class="bizClaimVoucherAction" method="{1}">
19             <interceptor-ref name="loginStack"></interceptor-ref><!-- 引用拦截器栈 -->
20 </action>
原文地址:https://www.cnblogs.com/taobd/p/6676782.html