• Spring中RequestContextHolder以及HandlerInterceptorAdapter的使用


    1 . RequestContextHolder 的使用

    想要使用RequestContextHolder,要在web.xml中配置RequestContextListener的监听才能使用。

    //全局获取session的方法:
    
    HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();

    同时 这样可以获取request和response。

    2 . HandlerInterceptorAdapter的使用

    在实现跳转到需要登录的页面时,除了用Shiro权限外,还可以通过在登录的方法上添加注解,如果有注解,发现没有登录的话,就跳转到登录页面。

    比如做一个登录拦截器

    /**
     * 前台专门用于登陆检查的拦截器
     */
    public class LoginCheckInterceptor extends HandlerInterceptorAdapter {
    
        //或者也可以用  implement  HandlerInterceptor 来做
    
        //适配器实现了HandlerInterceptor的所有方法  我们只需去覆盖需要用到的方法即可
    
        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response, Object handler) throws Exception {
            //判断登陆逻辑
            //判断当前请求的方法
            if (handler instanceof HandlerMethod) {  //HandlerMethod包装了我这次请求要访问的controller里的具体方法
                HandlerMethod hm = (HandlerMethod) handler;
                RequireLogin rl = hm.getMethodAnnotation(RequireLogin.class);//获取到当前方法上是否有注解
                //rl != null  说明该方法需要登陆才能访问
                if (rl != null && UserContext.getCurrent() == null) {
                    response.sendRedirect("/login.html");
                    return false; //阻止继续执行
                }
            }
            return super.preHandle(request, response, handler);   //正常的放行
        }
    }

    需要在applicationContext中配置拦截

    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
            <bean class="com.yl.p2p.base.util.LoginCheckInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
  • 相关阅读:
    PHP学习笔记二十八【抽象类】
    PHP学习笔记二十七【重写】
    PHP学习笔记二十六【类的重载】
    PHP学习笔记二十五【类的继承】
    BZOJ4001[TJOI2015]概率论(数学、期望、生成函数、卡特兰数)
    BZOJ5091摘苹果(概率、期望)
    [Codeforces1009E]Intercity Travelling 数学题
    ZJOI2009狼和羊的故事
    洛谷P2050[NOI2012]美食节(网络流+动态加边优化)
    apk编辑器制作共存失败的一个可能的原因(第一次手动制作的教训)
  • 原文地址:https://www.cnblogs.com/Jeely/p/10811945.html
Copyright © 2020-2023  润新知