攔截器不生效


解決思路:

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM