Spring Boot——通過原始碼探究靜態資源的映射規則
我們開發一個Spring Boot專案,肯定要匯入許多的靜態資源,比如css,js等檔案
如果我們是一個web應用,我們的main下會有一個webapp,我們以前都是將所有的頁面導在這里面的,對吧!但是我們現在的pom呢,打包方式是為jar的方式,那么這種方式SpringBoot能不能來給我們寫頁面呢?當然是可以的,但是SpringBoot對于靜態資源放置的位置,是有規定的!
1、靜態資源映射規則
1.1、第一種映射規則
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 這個配置類里面;
WebMvcAutoConfigurationAdapter 中有很多配置方法;其中就有一個添加資源處理方法:addResourceHandlers (),原始碼如下,
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
ServletContext servletContext = getServletContext();
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (servletContext != null) {
registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
}
});
}
通過分析上面原始碼可得,添加的靜態資源映射路徑為/webjars/**,資源路徑為classpath:/META-INF/resources/webjars/
什么是webjars
WebJars是將客戶端(瀏覽器)資源(JavaScript,Css等)打成jar包檔案,以對資源進行統一依賴管理,WebJars的jar包部署在Maven中央倉庫上,
webjars官網
我們可以到webjars官網上找到自己需要的資源,在自己的工程中添加入maven依賴,即可直接使用這些資源了,
比如,我們要匯入jquery資源
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
匯入后我們可以通過資源路徑找到資源的存放位置并訪問,我們在webjars網站匯入的資源都符合下圖的結構

通過路徑訪問,成功訪問到靜態資源!

1.2、第二種映射規則
下面我們繼續分析源碼

getStaticPathpattern():獲得靜態路徑模式,點進去看一下原始碼
public String getStaticPathPattern() {
return this.staticPathPattern;
}
再看一下staticPathPattern的原始碼

/**就是當前目錄下的所有靜態資源都能識別,但是當前目錄下具體指的又是什么呢?我們點開resourceProperties的原始碼便可看出來,原始碼如下:

上面原始碼很清楚的給出了我們四個靜態資源路徑,所以只要是這四個目錄下的靜態資源,都可以直接獲取,
我們來測驗一下,先補齊上面的目錄,然后再resource目錄放一個js資源

啟動springboot應用測驗:成功訪問到靜態資源!

1.3、總結
以下四個目錄存放的靜態資源可以被我們識別:
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
注意:
-
第一個目錄的訪問路徑為localhost:8080/webjars/資源目錄結構,后面三個訪問路徑為localhost:8080/資源名
-
第二種映射規則的優先級為:resources>static(默認)>public
2、自定義靜態資源路徑
我們可以自己通過組態檔來指定一下,哪些檔案夾是需要我們放靜態資源檔案的,在application.properties中配置;
spring.resources.static-locations=classpath:/coding/,classpath:/cheng/
但是通過下面原始碼我們可以看出,如果自定義了資源路徑,那么上面默認的四個路徑就失效了,所以最好不要自定義路徑,使用springboot幫我們自動配置好的就行,
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/282634.html
標籤:其他
上一篇:BOM 和 DOM
