關于SpringBoot攔截器攔截靜態(tài)資源的問題
SpringBoot攔截器攔截靜態(tài)資源
使用springboot2.0+的版本建立攔截器攔截訪問時,發(fā)現(xiàn)將靜態(tài)的css/js資源也攔截了。
此時需要在攔截器中配置放行資源。
直接上代碼
//設置攔截,釋放靜態(tài)文件
registry.addInterceptor(new LoginHandlerInterceptero()).addPathPatterns("/**")
.excludePathPatterns("/user/login","/login.html","/css/**","/js/**");放行"/css/**"資源。
有些使用放行static文件夾來放行所有的靜態(tài)資源,不過SpringBoot默認掃描static包下的靜態(tài)資源,所以好像不管用。
下圖是一次項目中配置的靜態(tài)資源釋放,

對文件結(jié)構(gòu)不是很清楚,所以直接配置釋放所有文件。
springboot攔截器為什么攔截靜態(tài)資源
項目目錄結(jié)構(gòu)如下所示
??
首先是以繼承的方式注冊攔截器配置
@Configuration
public class SpringMvcSupport_extends extends WebMvcConfigurationSupport {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//配置攔截器
registry.addInterceptor(loginInterceptor).
//對所有的資源進行攔截,包括靜態(tài)資源
addPathPatterns("/**")
.excludePathPatterns("/login.html","/js/**","/css/**","/lib/**");
}此時訪問靜態(tài)資源得到如下結(jié)果:

這種方式會攔截靜態(tài)資源我也不知道原因是什么希望后續(xù)補坑
但是如果以實現(xiàn)接口的形式來注冊攔截器的話就不會攔截靜態(tài)資源
@Configuration
public class SpringMvcSupport implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置攔截器
registry.addInterceptor(loginInterceptor).
//對所有的資源進行攔截,包括靜態(tài)資源
addPathPatterns("/**")
.excludePathPatterns("/login.html","/js/**","/css/**","/lib/**");
}運行項目此時訪問靜態(tài)資源就可以成功訪問:


這個問題卡了很久很久/(ㄒoㄒ)/~~
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- springboot設置加載靜態(tài)資源的路徑(spring.resources.static-locations)
- SpringBoot中的static靜態(tài)資源訪問、參數(shù)配置、代碼自定義訪問規(guī)則詳解
- springboot攔截器不攔截靜態(tài)資源,只攔截controller的實現(xiàn)方法
- springboot應用中靜態(tài)資源訪問與接口請求沖突問題解決
- SpringBoot2.x過后static下的靜態(tài)資源無法訪問的問題
- SpringBoot如何訪問html和js等靜態(tài)資源配置
- springboot+thymeleaf打包成jar后找不到靜態(tài)資源的坑及解決
- SpringBoot無法訪問/static下靜態(tài)資源的解決
- SpringBoot靜態(tài)資源及原理解析
相關文章
springboot集成redis并使用redis生成全局唯一索引ID
本文主要介紹了springboot集成redis并使用redis生成全局唯一索引ID,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

