首頁 >Java >java教程 >SpringBoot中靜態資源存取的方法

SpringBoot中靜態資源存取的方法

PHPz
PHPz轉載
2023-05-19 16:46:061509瀏覽

一、概述​​

springboot 預設靜態資源存取的路徑為:/static 或/public 或/resources 或/META-INF/resources 這樣的位址都必須定義在src/main/resources目錄檔案中,這樣可以達到在專案啟動時候可以自動載入為專案靜態位址目錄到classpath下,靜態存取位址其實是使用ResourceHttpRequestHandler 核心處理器載入到WebMvcConfigurerAdapter進行對addResourceHandlers方法進行覆寫.將靜態存取目錄進行重新定義。我們也可以實作其中方法,手動指定靜態存取路徑透過繼承WebMvcConfigurerAdapter重寫內部方法addResourceHandlers也可以達到我們想要的效果。

第一種方式: 放在src/main/webapp目錄下

#放在webapp目錄下的靜態資源是可以直接存取的

SpringBoot中靜態資源存取的方法

user.html

SpringBoot中靜態資源存取的方法

2.png

SpringBoot中靜態資源存取的方法

在user.html中引用2.png

SpringBoot中靜態資源存取的方法

第二種方式:放在classpath下

ResourceProperties中的說明

org.springframework.boot.autoconfigure.web.ResourceProperties
 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
   "classpath:/META-INF/resources/", "classpath:/resources/",
   "classpath:/static/", "classpath:/public/" };

靜​​態資源預設放在classpath路徑下:Defaults to classpath:[/META-INF/resources/,/resources/, /static/, /public/] plus context:/ (the root of the servlet context).

SpringBoot中靜態資源存取的方法

person/index.html

nbsp;html>


<meta>
<title>Insert title here</title>
<link>
<script></script>
<script>
 sayHello();
</script>


 <h4>person page HTML</h4>

SpringBoot中靜態資源存取的方法

#透過修改組態項,設定靜態資源的位置

application.properties
# 修改默认的静态资源存放目录
spring.resources.static-locations=classpath:/web/

SpringBoot中靜態資源存取的方法

以上是SpringBoot中靜態資源存取的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除