在web開發中,靜態資源的訪問時必不可少的,比如image、css、js等。springboot對靜態資源訪問提供了很好的支援,使用其提供的基本預設配置基本可以滿足開發需求,同時,又支援開發人員進行自定義配置。
spring boot 預設將 / 所有訪問對映到以下目錄:**
接下來,在main/resources下新建static、public和resources三個資料夾,分別放入a.png、b.png和c.png三張,如下:classpath:
/static
classpath:
/public
classpath:
/resources
classpath:
/meta-inf/resources
這裡寫描述
啟動專案,分別訪問:
/c.png發現都能正常訪問相應的資源。那麼說明,spring boot 缺省會挨個從 public、resources和static 裡面找是否存在相應的資源,如果有則直接返回。
自定義靜態資源對映類
追溯原始碼發現,在webmvcautoconfiguration類中,有如下**:
通過追溯public
void
addresourcehandlers
(resourcehandlerregistry registry)
else).
addresourcelocations
(new
string
).setcacheperiod
(this
.getseconds
(cacheperiod)).
setcachecontrol
(cachecontrol));
}// 此處做的就是靜態資源資料夾對映
string staticpathpattern =
this
.mvcproperties.
getstaticpathpattern()
;if(!registry.
(staticpathpattern)))
.addresourcelocations
(getresourcelocations
(this
.resourceproperties.
getstaticlocations()
)).setcacheperiod
(this
.getseconds
(cacheperiod)).
setcachecontrol
(cachecontrol));
}}}
staticpathpattern
,在resourceproperties
類中,發現如下常量資訊被設定:
到此,就可以發現,這就是spring boot為我們提供的預設靜態資源對映,那麼自定義對映規則的話,繼承webmvcconfigurer即可。如下:private
static
final string[
] classpath_resource_locations =
newstring
;
@configuration
public
class
mywebmvcconfig
implements
webmvcconfigurer
}
重啟專案,再訪問靜態資源,需要以mystatic開頭,如下:spring.mvc.
static
-path-pattern=
/mystatic/**
這樣,仍可以訪問之前的a b c三張。如果按照之前http://localhost:8083/a.png就不能再訪問到了。
重啟專案,訪問:# 配置靜態資源訪問字首
spring.mvc.
static
-path-pattern=
/mystatic/**
# 配置靜態資源路徑,預設配置失效
spring.resources.static-locations[0]=classpath:/mystatic
spring.resources.static-locations[1]=classpath:/public
發現可以正常訪問,同理,mystatic和static中靜態資源都可以正常訪問。
但當訪問resources和static裡靜態資源時,就會404報錯,訪問不到了,這個是因為配置檔案中如果進行了靜態資源路徑的配置,那麼預設的配置就失效了。
spring boot 靜態資源
springboot中,預設的靜態資源路徑有 配置在resourceproperties類中 private static final string classpath resource locations 優先順序 靜態資源路徑 例如 webmvcautoconfiguration自動裝配類中,可...
SpringMVC REST 風格靜態資源訪問配置
1 在web.xml中使用預設servlet處理靜態資源,缺點是如果靜態資源過多,則配置量會比較大,一旦有遺漏,則會造成資源無法正常顯示或404錯誤。2 在springmvc配置檔案中配置 我的所有靜態資源都在webcontent static 之下,下有如下目錄webcontent static ...
springboot載入靜態資源
使用springboot寫了簡單的web專案,頁面使用jsp檔案 但是靜態資源js 載入不到,看了下官方文件發現是因為路徑不對 所以專案靜態資源應該配置在根路徑下這四個資料夾中是可以直接訪問到的 meta inf resources,public,resources,static下的資源,對映路徑 ...