拦截器不生效

解决思路:

1、SpringMVC

   springMVC容器中需要添加相关配置,其中的

authenticationInterceptor就是目标拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean id="authenticationInterceptor" class="com.cloudwalk.shark.config.jwt.AuthenticationInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

2、SpringBoot

SpringBoot中的就需要区分是1.X还是2.X这个里面是有说法的,可以去网上百度

通过@Configuration注解将拦截器配置实现,这个只是其中一种方式;

@Configuration
public class WebJavaBeanConfiguration {
/**
* 日志拦截器
*/
@Autowired
private AuthenticationInterceptor authenticationInterceptor;

/**
* 实例化WebMvcConfigurer接口
*
* @return
*/
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
/**
* 添加拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**");
}
};
}
}

总结:如果拦截器没有生效:
1、你的拦截器没有被spring加载到,换句话你认为你配置了,但是没有生效,就像下面这种场景:

SpringBoot在配置拦截器后,拦截器不起作用
按照网上诸多博客配置了SpringBoot拦截器,最终却惊奇的发现,拦截器不起作用,百般查找原因,sackoverflower,google,baidu…, 均不能解决问题,后来经过@ComponentScan(basePackages={“com.netease.controller”})启发后,发现问题就在于此。
##原因就是:
Springboot的启动类XXXApplication不能扫描到拦截器配置类,可加上@ComponentScan(basePackages={“com.netease.interceptor”}),即可解决。其中com.netease.interceptor 为拦截器的注解配置类所在的路径。

##原因分析:
当controller类和Springboot的启动类XXXApplication不在同一个目录下时,Controller是无法被启动类的默认扫描器扫描到的,该扫描器只会扫描和XXXApplication在同一个目录下的注解配置。同理,如果想要拦截器的注解配置类也被扫描到,只需要加上@ComponentScan(basePackages={“com.netease.interceptor”})来告诉SpringBoot启动类的默认扫描器拦截器所在的目录,从而实现该拦截器注解类的正确扫描。
---------------------

2、你的拦截器已经生效了,只不过你请求的URL与设定的不匹配,但是你以为匹配上了,比如说你拦截的是/A/*,你输入的是/A

具体配置如下
必须加上@Configuration注解,这样里边的@Bean才能起作用,Spring才能统一管理当前的拦截器实例。
addPathPatterns("/api/**")配置拦截路径,其中/**表示当前目录以及所有子目录(递归),/*表示当前目录,不包括子目录。
https://blog.csdn.net/u012862619/article/details/81557779

原文地址:https://www.cnblogs.com/longxok/p/10844169.html