10. 静态资源处理
10.1 静态资源映射规则
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;
里面的静态内部类 WebMvcAutoConfigurationAdapter 中有很多配置方法;
有一个方法:addResourceHandlers 添加资源处理
@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();
// 第一种:webjars 配置
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
// 第二种:静态资源配置
// staticPathPattern = "/**"
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
所有的 /webjars/* , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源*
10.2 webjars
Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,现在直接导入依赖即可。
网站:https://www.webjars.org
以jQuery为例:
-
首先导入依赖
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency>
-
查看webjars目录结构,并访问jQuery.js
-
输入该路径http://localhost:8080/webjars/jquery/3.4.1/jquery.js即可访问
10.3 第二种静态资源映射规则
staticPathPattern的第二种映射规则 :/** , 访问当前项目的任意资源,它会进入resourceProperties
这个类
// 进入方法
public String[] getStaticLocations() {
return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS
// 找到路径,这4个路径会被识别,优先级从高到低,后三个都是在resources下创建,默认static
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
};
ResourceProperties 可以设置和静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。
10.4 自定义静态资源路径
# 一旦自定义静态文件夹的路径,自动配置就会生效
spring.resources.static-locations=classpath:/coding/,classpath:/indi/