SpringBoot 静态资源处理
SpringBoot自动配置的WebMvcAutoConfiguration.java
类
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
}
如果自定义了静态访问路径 则默认资源路径失效
-
所有
/webjars/**
都从classpath:/META-INF/resources/webjars/
路径下去找对应的静态资源。访问
http://127.0.0.1:8080/webjars/jquery/3.5.1/jquery.js
时候
![image-20210111102447404](https://img-blog.csdnimg.cn/img_convert/5fc8c1958f4e4743e92fdf49b22ba3bd.png)
通过 staticPathPattern 访问时
![image-20210111102532280](https://img-blog.csdnimg.cn/img_convert/68f32da666fc6e8be642be3d9b45874c.png)
this.resourceProperties.getStaticLocations()
获取静态资源路径
WebMvcAutoConfiguration
类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/: 当前项目根路径
优先级从高到低
首页 index
从静态资源目录获取index.html
如:/static/index.html
WebMvcAutoConfiguration
类自动为我们注册了如下文件为默认首页。
classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html
classpath:/public/index.html
/index.html