我们通过IDEA新建一个SpringBoot项目后,目录结构如下
通过Shift+Ctrl+N快捷键搜索WebMvcAutoConfiguration.class文件,进入此文件。我们在这个文件中找到一个名为WebMvcAutoConfigurationAdapter的静态类,找到此类下的addResourceHandlers(ResourceHandlerRegistry registry)方法,
代码如下:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//判断是否有自定义配置
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
方法的开始使用if语句判断是否有自定义配置,如果有则在日志输出**“默认资源配置失效”**。如果没有则继续下面的操作。下面的代码为我们提供了两种途径处理静态资源:
- webjars 访问方式为 localhost:8080/webjars/
- public,static,/**,resources 访问方式为localhost:8080/
优先级顺序为:META-INF/resources > resources > static > public。
我们可以通过在配置文件中修改spring.mvc.static-path-pattern来修改默认的映射路径,例如我修改为/hong/**,运行的时候访问 http://localhost:8080/hong/index.html 才会对应到index.html的页面。