拦截器的实现

一、关键类AbstractInterceptor,主要方法是:intercept

在SSH框架中实现操作权限可以使用拦截器,如果用户没有登陆不允许有操作,让他跳转到登陆页面。

可以使用下面方法实现

public class UserInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        //获取调用的方法名
        String methodName = invocation.getProxy().getMethod();
        
        //获取ActionContext
        ActionContext ac = invocation.getInvocationContext();
                
        if("login".equals(methodName) || "list".equals(methodName) || ac.getSession().get("userInfo") != null){
            return invocation.invoke();
        } else {
            return "login";
        }
    }

}

2 拦截器配置,在struts.xml配置文件中

<!-- 拦截器配置 -->
        <interceptors>
            <interceptor name="userInterceptor" class="com.huitong.action.UserInterceptor"></interceptor>
            <interceptor-stack name="myStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="userInterceptor"></interceptor-ref>
            </interceptor-stack>
            
        </interceptors>
        <!-- 执行指定的拦截器 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
原文地址:https://www.cnblogs.com/zhaopengcheng/p/6837690.html