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

Posted 叫我小锅锅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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/");//
    }
}

以上是关于SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题的主要内容,如果未能解决你的问题,请参考以下文章

spring boot框架学习8-干货spring boot的web开发-自定义拦截器处理权限

springboot生成excel并导出 拦截器设置

SpringBoot+拦截器+自定义异常+自定义注解+全局异常处理简单实现接口权限管理...

Springboot 自定义mybatis 拦截器,实现我们要的扩展

springboot怎么让自定义的拦截器优先于pagehelper执行

Springboot+自定义注解+自定义AOP前置增强+自定义异常+自定义异常捕获