新聞中心
簡介
在SpringBoot項目中,靜態(tài)資源是指不需要通過Web服務器處理的資源,如CSS、JavaScript、圖片等,訪問靜態(tài)資源的方法有很多,本文將介紹如何使用SpringBoot內置的靜態(tài)資源處理器來訪問靜態(tài)資源。

配置文件
在SpringBoot項目中,我們需要在application.properties或application.yml配置文件中進行一些配置,以便讓SpringBoot能夠正確地訪問靜態(tài)資源。
1、配置靜態(tài)資源路徑
在application.properties文件中,添加以下配置:
spring.resources.static-locations=classpath:/static/,file:/data/static/
或者在application.yml文件中,添加以下配置:
spring:
resources:
static-locations: classpath:/static/, file:/data/static/
這里我們將靜態(tài)資源分為兩部分:classpath:/static/和file:/data/static/,前者表示類路徑下的靜態(tài)資源,后者表示文件系統(tǒng)的靜態(tài)資源,你可以根據實際情況調整這些路徑。
2、配置默認緩存策略
在application.properties文件中,添加以下配置:
spring.resources.cache.period=3600s spring.resources.cache.control.max-age=86400s
或者在application.yml文件中,添加以下配置:
spring:
resources:
cache:
period: 3600s
control:
max-age: 86400s
這里我們設置了靜態(tài)資源的緩存周期為3600秒(1小時),并設置了最大緩存時間為86400秒(1天),你可以根據實際情況調整這些值。
3、配置編碼過濾器
為了確保瀏覽器能夠正確解析中文字符,我們需要配置一個編碼過濾器,在application.properties文件中,添加以下配置:
spring.resources.add-encoding-filter=true
或者在application.yml文件中,添加以下配置:
spring:
resources:
add-encoding-filter: true
這樣,SpringBoot就會自動為所有請求添加一個編碼過濾器,確保中文字符能夠正確顯示。
訪問靜態(tài)資源的方法
在SpringBoot項目中,我們可以使用以下方法來訪問靜態(tài)資源:
1、直接通過URL訪問:http://localhost:8080/static/css/style.css(假設我們的靜態(tài)資源放在了類路徑下的/static/css/style.css)
2、在HTML模板中引用:(假設我們的靜態(tài)資源放在了類路徑下的/static/css/style.css)
相關問題與解答
1、如何自定義靜態(tài)資源的存儲路徑?
答:在SpringBoot項目中,我們可以通過修改配置文件中的spring.resources.static-locations屬性來自定義靜態(tài)資源的存儲路徑,如果你想將靜態(tài)資源放在項目的根目錄下,可以將配置修改為:
spring.resources.static-locations=classpath:/,file:/data/custom_static/,file:${user.dir}/custom_static/
當前文章:如何使用SpringBoot訪問靜態(tài)資源
轉載來源:http://m.fisionsoft.com.cn/article/cohdppg.html


咨詢
建站咨詢
