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>
  • 相关阅读:
    MYSQL批量插入数据库实现语句性能分析【转】 批量插入!程序里面对于数据库插入的功能尽量用【异步处理+批量插入+(事务)】
    移动端如何解决页面返回上次浏览位置问题
    php对接java接口
    php后端遇到的问题
    jquery 判断字符串长度
    phpExcel常用方法详解
    html 手机端适配不同手机高度 ,把内容居中显示
    html 手机端 生成海报
    没错,老师就是个勤奋负责有良心的职业,不,的人
    睡眠是自然的第二道菜
  • 原文地址:https://www.cnblogs.com/lizijuna/p/11907399.html
Copyright © 2011-2022 走看看