生活随笔
收集整理的這篇文章主要介紹了
springboot指定首页(静态资源导入)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ResourceProperties小小的源碼分析
- 1. 靜態資源該放在哪里?
- 2. 首頁該如何自動展示?
1. 靜態資源該放在哪里?
springboot 集成了spring-webmvc,這個都是知道的。
該框架的特點是自動裝配。
先看WebMvcAutoConfiguration自動裝配類
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
));}}}
這是mvc幫我找到的資源位置
點進出跳到ResourceProperties這個類了
然后在點,找到了它是全局的字符數組,這里看著好像是個空的
再看構造器,賦值了!
數組是這個東西,不就是類路徑resouces目錄下嘛
private static final String
[] CLASSPATH_RESOURCE_LOCATIONS
= new String[]
{"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"};
可以在resources下傳教META-INF/resources, static/public/resources這四個文件夾,通過localhost:8080/xxx訪問到里面的靜態資源。
還有一個沒創建。
- 優先級
resources > static 默認 > public
2. 首頁該如何自動展示?
找到首頁,在WebMvcAutoConfiguration mvc相關得配置類中尋找
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");}
也是同上面放資源得數組一樣。放在四個目錄下面。
只要是index.html就是識別為首頁。便不會404.
總結
以上是生活随笔為你收集整理的springboot指定首页(静态资源导入)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。