struts2拦截器的使用

struts2登录验证

废话就不多说了直接把核心代码贴出来

struts2.xml的配置

<!-- 注册拦截器 -->
<interceptors>
    <interceptor name="AuthInterceptor" class="com.muke.employee.
        interceptor.AuthInterceptor">
    </interceptor>
    <!-- 自定义一个拦截器栈 myStack:含默认的拦截器:defaultStack 和 
        自己创建的拦截器:AuthInterceptor -->
    <interceptor-stack name="myStack">
        <interceptor-ref name="defaultStack"></interceptor-ref>
        <interceptor-ref name="AuthInterceptor">
            <!--  AuthInterceptor继承 MethodFilterInterceptor类,所以可以
                使用excludeMethods将某些方法排除在拦截器之外-->
            <param name="excludeMethods">login</param>
        </interceptor-ref>
    </interceptor-stack>
</interceptors>

service层的配置

package com.muke.employee.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/*
 * 用户自定义拦截器
 */
public class AuthInterceptor extends MethodFilterInterceptor {
    private static final long serialVersionUID = 1L;
    /* 创建的AuthInterceptor继承 MethodFilterInterceptor类,可以实现在struts.xml中对action中的方法不执行拦截 :
    <param name="excludeMethods">方法,如:login</param>  */
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        ActionContext ac=ActionContext.getContext();
        if(ac.getSession().get("existEmployee")!=null){
            String result=invocation.invoke();//invocation.invoke()返回的值是方法名,如login,saveUI,findAll
            System.out.println("拦截器中invocation.invoke()返回的值是方法名:"+result);
            return result;
        }else{
            System.out.println("AuthInterceptor拦截器拦截了您的操作,未登入或账号密码有误");
            return "login";
        }
    }
}

* 要其他实现代码的或看不懂的滴滴我。