Spring Boot系列笔记--静态资源映射规则
其他
2021-01-30 21:33:14
阅读次数: 0
一、webjars
- WebJars是以Jar形式为Web项目提供资源文件,然后借助Maven这些依赖库的管理,保证这些Web资源版本唯一性。
- 在spring boot源码中有一个自动配置类
WebMvcAutoConfiguration.class
,其中关于webjars的代码如下:...
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));
}
}
}
...
即所有/webjars/**
,都去 classpath:/META-INF/resources/webjars/
找资源
- 引入webjars依赖,以
jquery
和bootstrap
为例<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
- 查看导入的jar包
二、/**
访问当前项目资源
/**
访问当前项目的任何资源,都去(静态资源的文件夹)找映射
- 在
ResourceProperties.class
中定义了该搜索哪些静态资源文件夹private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
};
"/":当前项目的根路径
转载自blog.csdn.net/weixin_44863537/article/details/109074497