第一步:继承MethodFilterInterceptor写自己的自定义拦截器

 1 import org.apache.struts2.ServletActionContext;
 2 
 3 import com.opensymphony.xwork2.Action;
 4 import com.opensymphony.xwork2.ActionInvocation;
 5 import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
 6 
 7 /**
 8  * 登录的拦截器
 9  * @author anye
10  *
11  */
12 public class LoginInterceptor extends MethodFilterInterceptor{
13     private static final long serialVersionUID = 1L;
14 
15     @Override
16     protected String doIntercept(ActionInvocation arg0) throws Exception {
17         Object object = ServletActionContext.getRequest().getSession().getAttribute("admin");
18         if(object==null){
19             return Action.LOGIN;
20         }
21         return arg0.invoke();//递归调用拦截器
22     }
23 
24 }
View Code

第二步:在stuts.xml文件中配置自定义拦截器,并将自定义拦截器加入默认拦截器中,设置默认拦截器。

 

<!-- 拦截器 -->
        <interceptors>
            <interceptor name="login" class="com.tcrj.interceptor.LoginInterceptor"></interceptor>
            <interceptor-stack name="myStack">
                <interceptor-ref name="login">
                    <param name="excludeMethods">login</param>
                </interceptor-ref>
                <interceptor-ref name="paramsPrepareParamsStack" />
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myStack" />