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>
  • 相关阅读:
    HTML DOM 12 表格排序
    HTML DOM 10 常用场景
    HTML DOM 10 插入节点
    HTML DOM 09 替换节点
    HTML DOM 08 删除节点
    HTML DOM 07 创建节点
    022 注释
    024 数字类型
    005 基于面向对象设计一个简单的游戏
    021 花式赋值
  • 原文地址:https://www.cnblogs.com/Jeely/p/10811945.html
Copyright © 2011-2022 走看看