一、概述
springboot 默認(rèn)靜態(tài)資源訪問(wèn)的路徑為:/static 或 /public 或 /resources 或 /meta-inf/resources 這樣的地址都必須定義在src/main/resources目錄文件中,這樣可以達(dá)到在項(xiàng)目啟動(dòng)時(shí)候可以自動(dòng)加載為項(xiàng)目靜態(tài)地址目錄到classpath下 ,靜態(tài)訪問(wèn)地址其實(shí)是使用 resourcehttprequesthandler 核心處理器加載到webmvcconfigureradapter進(jìn)行對(duì)addresourcehandlers方法進(jìn)行覆蓋.將靜態(tài)訪問(wèn)目錄進(jìn)行重新定義。我們也可以實(shí)現(xiàn)其中方法,手動(dòng)指定靜態(tài)訪問(wèn)路徑通過(guò)繼承webmvcconfigureradapter重寫內(nèi)部方法addresourcehandlers也可以達(dá)到我們想要的效果。
第一種方式 : 放在src/main/webapp目錄下
放在webapp目錄下的靜態(tài)資源是可以直接訪問(wèn)的
user.html
2.png
在user.html中引用2.png
第二種方式:放在classpath下
resourceproperties中的說(shuō)明
1
2
3
4
|
org.springframework.boot.autoconfigure.web.resourceproperties private static final string[] classpath_resource_locations = { "classpath:/meta-inf/resources/" , "classpath:/resources/" , "classpath:/static/" , "classpath:/public/" }; |
靜態(tài)資源默認(rèn)放在classpath路徑下:defaults to classpath:[/meta-inf/resources/,/resources/, /static/, /public/] plus context:/ (the root of the servlet context).
person/index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!doctype html> <html> <head> <meta charset= "utf-8" > <title>insert title here</title> <link href= "/css/main.css" rel= "external nofollow" rel= "stylesheet" type= "text/css" /> <script type= "text/javascript" src= "/js/main.js" ></script> <script type= "text/javascript" > sayhello(); </script> </head> <body> <h3>person page html</h3> </body> </html> |
通過(guò)修改配置項(xiàng),設(shè)置靜態(tài)資源的位置
1
2
3
|
application.properties # 修改默認(rèn)的靜態(tài)資源存放目錄 spring.resources. static -locations=classpath:/web/ |
總結(jié)
以上所述是小編給大家介紹的在springboot中靜態(tài)資源訪問(wèn)方法,希望對(duì)大家有所幫助如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/w_x_z_/article/details/55657512