聊聊springboot靜態(tài)資源加載的規(guī)則
我們經(jīng)常會使用springboot創(chuàng)建web應(yīng)用,在springboot中金靜態(tài)資源是如何存放的呢?
靜態(tài)資源映射規(guī)則
我們先創(chuàng)建一個springboot項(xiàng)目。使用https://start.spring.io/idea內(nèi)置創(chuàng)建一個項(xiàng)目,不多說了。
我們要引入我們前端資源,我們項(xiàng)目中有許多的靜態(tài)資源,比如css,js等文件,我們以前寫
項(xiàng)目與都是自己建立文件夾,自己設(shè)計訪問路徑,但是現(xiàn)在,這個SpringBoot怎么處理呢?
如果我們是一個web應(yīng)用,我們的main下會有一個webapp,我們以前都是將所有的頁面導(dǎo)在
這里面的,對吧!但是我們現(xiàn)在的pom呢,打包方式是為jar的方式,那么這種方式
SpringBoot能不能來給我們寫頁面呢?當(dāng)然是可以的,但是SpringBoot對于靜態(tài)資源放置的位置,是有所差別的,有自己的一套規(guī)則!
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 這個配置類里面;我們可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;有一個方法:addResourceHandlers 添加資源處理
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//默認(rèn)配置沒有找到靜態(tài)資源
if (!this.resourceProperties.isAddMappings()) {
// 已禁用默認(rèn)資源處理
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
//webjars maven 引入靜態(tài)資源
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));
}
}
}
1.webjars
Webjars本質(zhì)就是以jar包的方式引入我們的靜態(tài)資源 , 我們以前要導(dǎo)入一個靜態(tài)資源文件,直接導(dǎo)入即可。
使用SpringBoot需要使用Webjars,我們可以去搜索一下:
網(wǎng)站:https://www.webjars.org
要使用jQuery,我們只要要引入jQuery對應(yīng)版本的pom依賴即可!
我們打開網(wǎng)站可以看到下面有很多前端js組件的maven引入。

<!--webjar 引入jquery-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
將這段引入放進(jìn)pom.xml文件,既可以在mavenjar包里面看到j(luò)query引入。

啟動項(xiàng)目訪問:http://localhost:8080/webjars/jquery/3.4.1/jquery.js即可看到j(luò)query.js

2.springboot內(nèi)置默認(rèn)訪問路徑
在WebMvcAutoConfiguration mvc核心類組件里面,我們看下面一行代碼,我們?nèi)フ襰taticPathPattern發(fā)現(xiàn)第二種映射規(guī)則 :/** , 訪問當(dāng)前的項(xiàng)目任意資源,它會去找 resourceProperties 這個類,我們可以點(diǎn)進(jìn)去看一下分析:
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));
}
ResourceProperties 可以設(shè)置和我們靜態(tài)資源有關(guān)的參數(shù);這里面指向了它會去尋找資源的文件夾,即上面數(shù)組的內(nèi)容。
所以:以下四個目錄存放的靜態(tài)資源可以被我們識別:
1.“classpath:/META-INF/resources/”,
2.“classpath:/resources/”,
3.“classpath:/static/”,
4. "classpath:/public/"
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;
public ResourceProperties() {
this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
this.addMappings = true;
this.chain = new ResourceProperties.Chain();
this.cache = new ResourceProperties.Cache();
}
public String[] getStaticLocations() {
return this.staticLocations;
}
我們可以在resources根目錄下新建對應(yīng)的文件夾,都可以存放我們的靜態(tài)文件;
比如我們訪問 http://localhost:8080/test.js , 他就會去這些文件夾中尋找對應(yīng)的靜態(tài)資源文件;

分別在四個目錄下面建立一個test.js文件,我們分別測試一下。

四個目錄都有test.js,我們發(fā)現(xiàn)優(yōu)先加載resourse下面的文件。
刪除resourse下面的test.js,再次查看一下,發(fā)現(xiàn)加載的是static下面的文件。

同樣,刪除static下面的文件在試一下:執(zhí)行了public

最后刪除public下面的文件:

我們可以發(fā)現(xiàn),springboot加載靜態(tài)資源文件的優(yōu)先級:resourse>static>public>META-INF
我們也可以自己通過配置文件來指定一下,哪些文件夾是需要我們放靜態(tài)資源文件的,在application.properties中配置;
spring.resources.static-locations=classpath:/coding/,classpath:/cpown/
一旦自己定義了靜態(tài)文件夾的路徑,原來的自動配置就都會失效了!
3.首頁處理
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
private Optional<Resource> getWelcomePage() {
String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
這是加載默認(rèn)歡迎頁,靜態(tài)資源文件夾下的所有 index.html 頁面;被 /** 映射。
比如我訪問 http://localhost:8080/ ,就會找靜態(tài)資源文件夾下的 index.html
新建一個 index.html ,在我們上面的3個目錄中任意一個;然后訪問測試 http://localhost:8080/ 看結(jié)果!


4.網(wǎng)站圖標(biāo)
與其他靜態(tài)資源一樣,Spring Boot在配置的靜態(tài)內(nèi)容位置中查找 favicon.ico。如果存在這樣的文件,它將自動用作應(yīng)用程序的favicon。
1、關(guān)閉SpringBoot默認(rèn)圖標(biāo)
#關(guān)閉默認(rèn)圖標(biāo) spring.mvc.favicon.enabled=false
2、自己放一個圖標(biāo)在靜態(tài)資源目錄下,我放在 public 目錄下
3、清除瀏覽器緩存!刷新網(wǎng)頁,發(fā)現(xiàn)圖標(biāo)已經(jīng)變成自己的了!


以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java如何導(dǎo)入Jsoup庫做一個有趣的爬蟲項(xiàng)目
Jsoup庫是一款Java的HTML解析器,可用于從網(wǎng)絡(luò)或本地文件中獲取HTML文檔并解析其中的數(shù)據(jù),這篇文章給大家介紹Java導(dǎo)入Jsoup庫做一個有趣的爬蟲項(xiàng)目,感興趣的朋友跟隨小編一起看看吧2023-11-11
java實(shí)現(xiàn)圖像轉(zhuǎn)碼為字符畫的方法
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖像轉(zhuǎn)碼為字符畫的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Java使用Graphics2D實(shí)現(xiàn)字符串文本自動換行
這篇文章主要為大家詳細(xì)介紹了Java如何使用Graphics2D實(shí)現(xiàn)字符串文本自動換行,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
SpringBoot集成RabbitMQ的方法(死信隊(duì)列)
這篇文章主要介紹了SpringBoot集成RabbitMQ的方法(死信隊(duì)列),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
JVM?運(yùn)行時數(shù)據(jù)區(qū)與JMM?內(nèi)存模型
這篇文章主要介紹了JVM?運(yùn)行時數(shù)據(jù)區(qū)與JMM?內(nèi)存模型,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值。需要的朋友可以參考一下2022-07-07
Java實(shí)現(xiàn)SHA-256加密算法的完全解析
SHA-256是一種散列(哈希)算法,用于將任意長度的數(shù)據(jù)映射為固定長度的散列值,以保證數(shù)據(jù)完整性。本文將為大家介紹一下SHA-256加密算法的原理與實(shí)現(xiàn),希望對大家有所幫助2023-02-02
Spring MVC簡介_動力節(jié)點(diǎn)Java學(xué)院整理
Spring MVC屬于SpringFrameWork的后續(xù)產(chǎn)品,已經(jīng)融合在Spring Web Flow里面。今天先從寫一個Spring MVC的HelloWorld開始,讓我們看看如何搭建起一個Spring mvc的環(huán)境并運(yùn)行程序,感興趣的朋友一起學(xué)習(xí)吧2017-08-08

