【spring boot】第4篇:spring boot對靜態資源的管理
spring boot 對 web 靜態資源的配置管理是通過配置類 WebMvcAutoConfiguration
來實現的。
WebMvcAutoConfiguration 的理解
顧名思義,WebMvcAutoConfiguration 是web開發的相關配置都放在該類中的。那我們看看靜態資源是如何配置的呢?
addResourceHandlers 方法中對靜態資源路徑做了說明
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(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } //staticPathPattern的值是 /** 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包的形式引入靜態資原始檔
- ofollow,noindex" target="_blank">webjars官方網站
- 比如我們現在要使用 jquery 框架,在webjars官網找到他的依賴放到你的專案當中即可
<dependency> <groupId>org.webjars.bower</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
-
如果路徑是
/**
時,就去以下classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/
類路徑查詢資原始檔,idea 中的專案路徑如下圖所示:
3.歡迎頁面的對映
private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); }
意思是隻要在我們的靜態資原始檔夾中放有 index.html檔案,就能自動訪問到,比如: http://localhost :8080