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));
}
// 静态资源配置
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/
找对应的资源;
webjars
以jar
包形式引入我们的静态资源。
要使用jQuery
,需要引入jQuery
对应版本的pom
依赖即可!
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
在包中可以看到如下所示:
访问:http://localhost:8080/webjars/jquery/3.4.1/jquery.js
2. 静态资映射规则
我们去找staticPathPattern
发现第二种映射规则 :/** , 访问当前的项目任意资源,它会去找resourceProperties
这个类
// 进入方法
public String[] getStaticLocations() {
return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
};
ResourceProperties
可以设置和我们静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。
所以得出结论,以下四个目录存放的静态资源可以被我们识别:
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
例如在static下建一个test.js
优先级为:resources>static>public
- 自定义静态资源路径
在application.properties
中配置;
spring.resources.static-locations=classpath:/test/,classpath:/chen/
一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!