一、默認靜態資源訪問策略
(1)當我們使用 IntelliJ IDEA 創建 Spring Boot 項目,會默認創建 classpath:/static/ 目錄,我們直接把靜態資源放在這個目錄下即可。
(2)我們直接在瀏覽器中輸入“http://localhost:8080/1.png”即可看到我們添加的這張圖片。
二、自定義策略
如果默認的靜態資源過濾策略不能滿足開發需求,也可以自定義靜態資源過濾策略,自定義的方式有如下兩種。
1,在配置文件中定義
(1)我們在 application.properties 中直接定義過濾規則和靜態資源位置:
- 過濾規則改為 /static
- 靜態資源位置仍然是 classpath:/static/ 沒有變化
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/
yml版本
spring:
mvc:
static-path-pattern:/static/**
resources:
static-locations:classpath:/static/
(2)重啟項目,我們這次可以在瀏覽器中輸入“http://localhost:8080/static/1.png”來訪問添加的靜態圖片。
2,通過 Java 編碼定義
(1)這種方式我們只要創建一個類繼承 WebMvcConfigurer 接口即可,然后實現該接口的 addResourceHandlers 方法。
import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 靜態資源映射 */ @Component public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } }
(2)重啟項目,效果同上面是一樣的。我們同樣可以在瀏覽器中輸入“http://localhost:8080/static1.png”來訪問添加的靜態圖片。