Spring Boot 拦截器无效,不起作用

2022-07-02 09:05:43

这个问题一般是解决WebMvcConfigurerAdapter过时问题造成的。导致这个问题可能有两个原因:一个是拦截器写错了,另一个是拦截器配置错了。

1、需求是这样的

拦截所有的api请求,判断其请求头中的secret参数是否正确,正确的请求才能访问api

2、拦截器配置

需要先写拦截器,然后再配置到Spring Boot环境中。

2.1、写一个拦截器

Spring MVC中,拦截器有两种写法:要么实现HandlerInterceptor接口,要么实现WebRequestInterceptor接口,具体内容请看这里详述Spring MVC 框架中拦截器Interceptor 的使用方法
Spring Boot也只是集成了Spring MVC而已,所以拦截器的写法还是一样的。不一样的是Spring MVC的拦截器需要在xml文件中配置,而Spring Boot只需要在类上加@Component注解即可,这样当前拦截器才会被扫描到。
这里只需要实现HandlerInterceptor接口即可(这里没啥坑)。

/**
 * author : 颜洪毅
 * e-mail : yhyzgn@gmail.com
 * time   : 2019-08-29 17:44
 * version: 1.0.0
 * desc   : 用户拦截器
 */@ComponentpublicclassUserInterceptorimplementsHandlerInterceptor{privatestatic Logger log= Logger.getLogger(UserInterceptor.class);@Autowiredprivate UserThreadLocal local;@OverridepublicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        log.info("接收到请求");
        local.set(request.getParameter("user"));returntrue;}@OverridepublicvoidafterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception{
        local.remove();
        log.info("请求响应完成");}}

2.2、将拦截器配置到Spring Boot环境中

目前(2.0.4.RELEASE版本)WebMvcConfigurerAdapter已过时,如果你执意要用的话,应该没啥坑。但是被强迫症时刻针对的人,坑就来啦。
WebMvcConfigurerAdapter过时了,那么用谁来代替呢?机智的人可能早就发现了,过时的这个只不过是个适配器(适配器模式),那就可以直接使用它所实现的那个接口啊,就是WebMvcConfigurer呗。对,就是这个,别犹豫了。。我就被百度坑得不轻,具体说说怎么被坑的吧。

  • 百度后我查到的解决方案这样的

    两种方法,并且都还强烈推荐第二种方法

// 方法一:实现WebMvcConfigurer接口publicclassWebConfigimplementsWebMvcConfigurer{// ...}// 方法二:继承WebMvcConfigurationSupport类publicclassWebConfigextendsWebMvcConfigurationSupport{// ...}

于是就直接用了第二种方法,写完跑了项目发现没啥效果,打日志也出不来。然后又改回第一种方法,果然,有效果了。

具体配置如下
必须加上@Configuration注解,Spring才能统一管理当前的拦截器实例。
addPathPatterns("/api/**")配置拦截路径,其中/**表示当前目录以及所有子目录(递归),/*表示当前目录,不包括子目录。

/**
 * author : 颜洪毅
 * e-mail : yhyzgn@gmail.com
 * time   : 2019-08-29 17:48
 * version: 1.0.0
 * desc   : mvc配置
 */@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@Autowiredprivate UserInterceptor interceptor;@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){// 添加拦截器,配置拦截地址
        registry.addInterceptor(interceptor).addPathPatterns("/api/**");}}

不出意外的话,你的拦截器应该起作用啦!

  • 作者:天狼守徒
  • 原文链接:https://blog.csdn.net/u012862619/article/details/81557779
    更新时间:2022-07-02 09:05:43