spring boot 訪問靜態位址

2021-08-21 05:34:12 字數 1609 閱讀 5148

在web開發中,靜態資源的訪問是必不可少的,如:、js、css 等資源的訪問。

spring boot 對靜態資源訪問提供了很好的支援,基本使用預設配置就能滿足開發需求。

spring boot 對靜態資源對映提供了預設配置

spring boot 預設將 /** 所有訪問對映到以下目錄:
classpath:/static

classpath:/public

classpath:/resources classpath:/meta-inf/resources

如:在resources目錄下新建 public、resources、static 三個目錄,並分別放入 a.jpg b.jpg c.jpg

瀏覽器分別訪問:

均能正常訪問相應的資源。那麼說明,spring boot 缺省會挨個從 public resources static 裡面找是否存在相應的資源,如果有則直接返回。

在實際開發中,可能需要自定義靜態資源訪問路徑,那麼可以繼承webmvcconfigureradapter來實現。

package com.sam.demo.conf;

import org.springframework.context.annotation.configuration;

import org.springframework.web.servlet.config.annotation.resourcehandlerregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; /** * 配置靜態資源對映 * @author sam * @since 2017/7/16 */ @configuration public class webmvcconfig extends webmvcconfigureradapter }

重啟專案,訪問:http://localhost:8080/static/c.jpg 能正常訪問static目錄下的c.jpg資源。
spring.mvc.static-path-pattern=/static/**

重啟專案,訪問:http://localhost:8080/static/c.jpg 同樣能正常訪問static目錄下的c.jpg資源。

注意:通過spring.mvc.static-path-pattern這種方式配置,會使spring boot的預設配置失效,也就是說,/public /resources 等預設配置不能使用。

配置中配置了靜態模式為/static/,就只能通過/static/來訪問。

轉至:

springboot 訪問靜態資源

最近在做springboot 專案遇到靜態資源訪問問題,在這裡記錄下,可以給他人參考避免踩坑 問題點 sprignboot專案建立時預設自動建立靜態資源資料夾resources static和resources templates,預設可直接訪問靜態資源路勁有四類 static,public,res...

spring boot 訪問靜態資源

1.通過從classpath static目錄下 注意必須是static這個目錄。注意,在idea 社群版,第二種方式,無法實現,社群版沒有web外掛程式 無法實現,詳細步驟見 新建乙個工程 spt statics resources,1.pom檔案 org.springframework.boot...

訪問SpringBoot靜態資源

第一步 在pom.xml檔案中新增一下依賴 springboot訪問靜態資源的jar檔案 org.springframework.boot groupid spring boot starter thymeleaf artifactid dependency 第二步 找到resources資料夾下的...