zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    windows10 + anaconda + tensorflow-1.5.0 + python-3.6 + keras-2.2.4配置和安装
    k-center问题-学习
    交换机+路由器 网络口连接桥接关系示意
    用scp命令来通过ssh传输文件,ssh推送.py程序到CentOS7服务器端出现lost connection错误
    codevs 1519 过路费 最小生成树+倍增
    10.18 noip模拟试题
    poj 3565 ants
    [国家集训队2011]种树 (神贪心~~)
    poj 1821 Fence 单调队列优化dp
    SPFA 小优化*2
  • 原文地址:https://www.cnblogs.com/Jeely/p/10811945.html
Copyright © 2011-2022 走看看