spring boot mvc系列-靜態資源配置與MappingHandler攔截器
阿新 • • 發佈:2018-11-25
靜態資源配置
Spring Boot 預設將 /** 所有訪問對映到以下目錄:
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources
如果需要自定義對映目錄,可以繼承WebMvcConfigurerAdapter或WebMvcConfigurationSupport,以後者為例,如下:
@Configuration public class WebConfig extends WebMvcConfigurationSupport { @Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) { //將所有/static/** 訪問都對映到classpath:/static/ 目錄下 registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/"); registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/static/resources/"); registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/"); registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/"); registry.addResourceHandler("/font/**").addResourceLocations("classpath:/static/font/"); registry.addResourceHandler("/themes/**").addResourceLocations("classpath:/static/themes/"); } }
如果使用了攔截器HandlerInterceptor,好像覆蓋addResourceHandlers方法,似乎excludePathPatterns並沒有生效,不覆蓋的話前臺會報404。
攔截器配置
同樣在WebConfig中配置,如下:
package com.hundsun.ta.aop.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import com.hundsun.ta.interceptor.SecurityInteceptor; @Configuration public class WebConfig extends WebMvcConfigurationSupport { // 需要注意的是HandlerInteceptor必須通過@Bean配置,直接新增@new SecurityInteceptor()會導致依賴類未注入 @Bean SecurityInteceptor securityInteceptor() { return new SecurityInteceptor(); } @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(securityInteceptor()).excludePathPatterns("/css/**", "/js/**", "/font/**", "/images/**", "/resources/**", "/themes/**"); super.addInterceptors(registry); } }