• SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题


     

    自定义拦截器

    /**
     * UserSecurityInterceptor
     * Created with IntelliJ IDEA.
     * Author: yangyongkang
     * Date: 2018/8/22
     * Time: 14:20
     */
    @Component
    public class UserSecurityInterceptor implements HandlerInterceptor {
        @Autowired
        private RedisTemplate<String, Serializable> redisCacheTemplate;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            UserModel info = (UserModel) redisCacheTemplate.opsForValue().get(request.getSession().getId());
            if (info == null || StringUtils.isEmpty(info)) {
                response.sendRedirect(request.getContextPath() + "/view/login");
                return false;
            }
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        }
    }

    配置访问路径及静态资源

    /**
     * 登陆拦截控制类
     * Created with IntelliJ IDEA.
     * Author: yangyongkang
     * Date: 2018/8/22
     * Time: 14:17
     */
    @Configuration
    public class WebMvcConfig implements  WebMvcConfigurer {
        @Autowired
        private UserSecurityInterceptor securityInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            InterceptorRegistration addInterceptor = registry.addInterceptor(securityInterceptor);
            // 排除配置
            addInterceptor.excludePathPatterns("/error");
            addInterceptor.excludePathPatterns("/static/**");//排除静态资源
            addInterceptor.excludePathPatterns("/view/login");
            addInterceptor.excludePathPatterns("/login/check");
            // 拦截配置
            addInterceptor.addPathPatterns("/**");
        }
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");//
        }
    }
  • 相关阅读:
    Linux基础3-1 Bash及其特性
    三、手写ORM实现数据库更新
    三、TCP协议
    一、OIS七层模型及数据传输过程
    泛型缓存原理
    树莓派公网服务器实现frp内网穿透
    Dto数据传输对象
    Ubuntu下 Nginx静态代理部署网页常见报错
    JWT权限验证
    解决传入的请求具有过多的参数,该服务器支持最多 2100 个参数
  • 原文地址:https://www.cnblogs.com/lhboke/p/13270065.html
Copyright © 2020-2023  润新知