zoukankan      html  css  js  c++  java
  • SpringMVC编写登录权限拦截器

    一. 什么是登录权限拦截器?

      一个网站总会有页面是需要用户已经登录过才能访问的,比如购物车,个人详情页等等,拦截器可以对访问这些页面的请求做一个拦截,在判断是否存有用户登陆后的cookie或者session之后对其放行或者是重定向到登录页面。

    二. 编写登录拦截器

    /**
     * 〈访问需要登录的网站被拦截,没有登录则转到登录页面〉
     * @author 龙
     * @create 2018/8/23 22:01
     * @since 1.0.0
     */
    public class LoginInterceptor implements HandlerInterceptor {
    
        @Autowired
        private JedisService jedisService;
        //与SSO中字符串对应,不要轻易更改
        private static final String USER_LOGIN="gfsdgvafvqweac:";
        private Logger LOGGER=LoggerFactory.getLogger(LoginInterceptor.class);
    
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest,
                     HttpServletResponse httpServletResponse, Object o) throws Exception {
            //获取用户登陆后的令牌
            Cookie[] cookies=httpServletRequest.getCookies();
            String token=null;
            for (Cookie cookie:cookies) {//解析cookie
                if("token".equals(cookie.getName()))  token=cookie.getValue();
            }
            if(StringUtils.isEmpty(token)){//查找令牌,没有令牌则返回登录页面
                LOGGER.info("没有查找到令牌,返回登录页面");
                httpServletResponse.sendRedirect("/user/login.html");
                return false;
            }
    
    
            User user=JSONUtils.jsonToPojo(jedisService.get(USER_LOGIN+token),User.class);
            if(user==null)  {
                LOGGER.info("令牌无效或过期,返回登录页面");
                httpServletResponse.sendRedirect("/user/login.html");
                return false;
            }
            //用户登录状态有效,验证通过,转到欲访问的页面
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest,
                   HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest,
                    HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    
        }
    }

    三. 拦截器配置:springmvc.xml

        <!--配置权限拦截器,拦截所有需要登录才能访问的页面-->
        <mvc:interceptors>
            <mvc:interceptor>
                <!--对下面路径进行拦截,可配置多个路径-->
                <mvc:mapping path="/user/cart.html"/>
                <!--使用下面拦截器进行拦截-->
                <bean class="org.lizi.interceptor.LoginInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
  • 相关阅读:
    page1
    CodeForces
    树、递归————二叉树的所有路径
    树(未完)
    树、递归、遍历————二叉搜索树的最近公共祖先
    树、递归————翻转二叉树
    树、递归————路径总和
    树、递归、广度优先搜索(BFS)————二叉树的最小深度
    树————平衡二叉树
    平衡二叉树AVL
  • 原文地址:https://www.cnblogs.com/lizijuna/p/11907399.html
Copyright © 2011-2022 走看看