自定义拦截器——实现用户未登录自动跳转到登录页面

1.用户未登录自动跳转到登录页面

1.1 编写拦截器类

需要继承struts2的框架的MethodFilterInterceptor

提供的工具类(用于获取session中的数据和用户信息):

/**
 * 
 * @Title: BOSUtils  
 * @Description:   BOS项目工具类
 * @author YuKai Fan  
 * @date 2018年5月14日
 */
public class BOSUtils {
    //获取session对象
    public static HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
    
    //获取登录用户对象
    public static User getLoginUser() {
        return (User) getSession().getAttribute("loginUser");
    }
}

定义拦截器类:

/**
 * 
 * @Title: BOSLoginInterceptor  
 * @Description:  自定义拦截器,实现用户未登录自动跳转到登录页面
 * @author YuKai Fan  
 * @date 2018年5月14日
 */
public class BOSLoginInterceptor extends MethodFilterInterceptor {

    /**
     * 拦截方法
     */
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        //获取拦截的url地址
        /*ActionProxy proxy = invocation.getProxy();
        String actionName = proxy.getActionName();
        String namespace = proxy.getNamespace();
        String url = actionName + namespace;*/
        //从session中获取拦截对象
        User user = BOSUtils.getLoginUser();
        if (user == null) {
            //没有登录,跳转到登录页面
            return "login";
        }
        //放行
        return invocation.invoke();
    }

}

1.2 配置拦截器

在struts.xml中配置自定义拦截器:

<!-- 配置拦截器 -->
        <interceptors>
            <!-- 注册拦截器 -->
            <interceptor name="bosLoginInterceptor" class="com.javaweb.bos.web.interceptor.BOSLoginInterceptor">
                <!-- 指定哪些方法不需要拦截 -->
                <param name="excludeMethods">login</param>
            </interceptor>
            <!-- 定义拦截器栈 -->
            <interceptor-stack name="myStack">
                <interceptor-ref name="bosLoginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        <!-- 配置全局结果集 -->
        <global-results>
            <result name="login">/login.jsp</result>
        </global-results>

猜你喜欢

转载自www.cnblogs.com/FanJava/p/9034663.html
今日推荐