1、默認靜態資源映射
Spring Boot對靜態資源映射提供了默認配置
Spring Boot默認將 /** 所有訪問映射到一下目錄
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
在resources目錄下新建 META-INF/resources、public、resources、static 四個目錄,並分別放入 4.jpg 3.jpg 2.jpg 1.jpg圖片
啟動項目,在瀏覽器分別輸入
http://localhost:8080/4.jpg
http://localhost:8080/3.jpg
http://localhost:8080/2.jpg
http://localhost:8080/1.jpg
例如:
2、自定義靜態資源文件訪問
(1)、第一種方式:配置類
將所有C:\\Users\\Administrator\\Pictures\\Fairy\\訪問都映射到/myPic/**路徑下
重啟項目后,例如在C:\Users\Administrator\Pictures\Fairy中有一張1.jpg圖片,
在瀏覽器輸入http://localhost:8080/myPic/1.jpg即可訪問
(2)、配置application.properties
web.upload-path=C:\Users\Administrator\Pictures\Fairy
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
web.upload-path:這個屬於自定義的屬性,指定了一個路徑,注意要以/結尾;
spring.mvc.static-path-pattern=/**:表示所有的訪問都經過靜態資源路徑;
spring.resources.static-locations:在這里配置靜態資源路徑,前面說了這里的配置是覆蓋默認配置,所以需要將默認的也加上否則static、public等這些路徑將不能被當作靜態資源路徑,在這個最末尾的file:${web.upload-path}之所有要加file:是因為指定的是一個具體的硬盤路徑,其他的使用classpath指的是系統環境變量。
重啟項目,例如在C:\Users\Administrator\Pictures\Fairy下有一張lion.jpg
在瀏覽器地址中輸入http://localhost:8080/lion.jpg即可