靜態資源對映規則

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));
}
// 靜態資源配置
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 呢?

Webjars本質就是以jar包的方式引入我們的靜態資源 , 我們以前要匯入一個靜態資原始檔,直接匯入即可。

使用SpringBoot需要使用Webjars,我們可以去搜索一下:

網站:https://www.webjars.org

要使用jQuery,我們只要要引入jQuery對應版本的pom依賴即可!

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

匯入完畢,檢視webjars目錄結構,並訪問Jquery.js檔案!

訪問:只要是靜態資源,SpringBoot就會去對應的路徑尋找資源,我們這裡訪問:http://localhost:8080/webjars/jquery/3.4.1/jquery.js

第二種靜態資源對映規則

那我們專案中要是使用自己的靜態資源該怎麼匯入呢?我們看下一行程式碼;

我們去找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/"

我們可以在resources根目錄下新建對應的資料夾,都可以存放我們的靜態檔案;

比如我們訪問 http://localhost:8080/1.js , 他就會去這些資料夾中尋找對應的靜態資原始檔;

我們也可以自己通過配置檔案來指定一下,哪些資料夾是需要我們放靜態資原始檔的,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/zwt/

一旦自己定義了靜態資料夾的路徑,原來的自動配置就都會失效了!

參考連結

狂神說SpringBoot10:Web開發靜態資源處理 (qq.com)