springboot 2.0+ 自定義攔截器 靜態資源問題
阿新 • • 發佈:2018-09-03
per static index 進行 onf 自定義攔截器 tor gis css
之前項目的springboot自定義攔截器使用的是繼承WebMvcConfigurerAdapter重寫常用方法的方式來實現的.靜態文件不需要進行放行,springboot會自動幫你放行。
springboot2.0之後如果想要自定義的話就不可以了,需要手動放行靜態資源。此處我是實現了WebMvcConfigurer來自定義攔截器(根據需求也可以繼承WebMvcConfigurationSupport,此處不再贅述)。下面是實現代碼
@Configuration public class MyMvcConfig implements WebMvcConfigurer { //所有的WebMvcConfigurerAdapter組件都會一起起作用@Bean //將組件註冊在容器 public WebMvcConfigurer webMvcConfigurer(){ WebMvcConfigurer adapter = new WebMvcConfigurer() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); } //註冊攔截器 @Override public void addInterceptors(InterceptorRegistry registry) { //super.addInterceptors(registry);//靜態資源; *.css , *.js //SpringBoot已經做好了靜態資源映射 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("**") .excludePathPatterns("/index.html","/","/hello1","/user/login") .excludePathPatterns("/static/**"); } }; return adapter; } }
註意:(大坑)此處的addPathPatterns("**")不要使用 “/**”,否則靜態資源還是會被攔截
springboot 2.0+ 自定義攔截器 靜態資源問題