默認(rèn)靜態(tài)資源供
SpringBoot有幾個默認(rèn)的靜態(tài)資源目錄,當(dāng)然也可配置,默認(rèn)配置的/**映射到/static(或/public ,/resources,/META-INF/resources),自定義配置方式如下:
1
|
spring.mvc. static -path-pattern=/** # Path pattern used for static resources. |
前端如果需要訪問默認(rèn)的靜態(tài)資源,下面有點要注意,考慮下面的目錄結(jié)構(gòu):
1
2
3
4
5
6
7
8
9
10
11
12
|
└─resources │ application.yml │ ├─ static │ ├─css │ │ index.css │ │ │ └─js │ index.js │ └─templates index.html |
在index.html中該如何引用上面的靜態(tài)資源呢?
如下寫法:
1
2
|
<link rel= "stylesheet" type= "text/css" href= "/css/index.css" rel= "external nofollow" > <script type= "text/javascript" src= "/js/index.js" ></script> |
注意:默認(rèn)配置的/**映射到/static(或/public ,/resources,/META-INF/resources)
當(dāng)請求/css/index.css的時候,Spring MVC 會在/static/目錄下面找到。
如果配置為/static/css/index.css,那么上面配置的幾個目錄下面都沒有/static目錄,因此會找不到資源文件!
所以寫靜態(tài)資源位置的時候,不要帶上映射的目錄名(如/static/,/public/ ,/resources/,/META-INF/resources/)!
自定義靜態(tài)資源
網(wǎng)上資料說可以在配置文件中定義指定,我沒有用這種方式,我使用的是通過實現(xiàn)擴(kuò)展Configuration來實現(xiàn)。
PS:說明一下在SpringBoot 1.x的版本中,都是通過繼承WebMvcAutoConfiguration來擴(kuò)展一些與Spring MVC相關(guān)的配置,但在2.x的版本中,直接實現(xiàn)接口WebMvcConfigurer來擴(kuò)展Spring MVC的相關(guān)功能,如配置攔截器,配置通用返回值處理器,配置統(tǒng)一異常處理等,當(dāng)然還包括配置本文中的自定義靜態(tài)資源路徑,覆蓋里面等default方法即可。
直接上代碼吧:
1
2
3
4
5
6
7
8
9
10
11
|
@Configuration public class MyWebAppConfigurer implements WebMvcConfigurer { // event.share.image.dir=/data/share/image/ @Value ( "${event.share.image.dir}" ) private String outputDir; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/share/image/**" ).addResourceLocations( "file:" +outputDir); } } |
說明:上面代碼的背景是從別的地方動態(tài)拿過來的圖片,肯定不能在放到SringBoot的jar包中了,于是通過以上配置可以就可通過http://host/share/image/a.jpg直接訪問在/data/share/image/a.jpg圖片了。如果靜態(tài)資源文件不是動態(tài)的,也在resources目錄下面,只是需要下面這樣寫即可:
1
2
|
registry.addResourceHandler( "/share/image/**" ).addResourceLocations( "classpath:" +outputDir); // 把file換成classpath |
通過SpringBoot工具類訪問靜態(tài)資源
很簡單,代碼如下:
1
2
3
|
private static final String BACKGROUND_IMAGE = "share/background.jpg" ; File file = new ClassPathResource(BACKGROUND_IMAGE).getFile(); InputStream is = new ClassPathResource(BACKGROUND_IMAGE).getInputStream(); |
原來還有一種寫法:
1
2
|
private static final String BACKGROUND_IMAGE = "classpath:share/background.jpg" ; File file = ResourceUtils.getFile(BACKGROUND_IMAGE); |
但在2.x版本中,可能出現(xiàn)下面但異常
java.io.FileNotFoundException: class path resource [share/background.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/ubuntu/wxcs/calendar-api-1.0.0.jar!/BOOT-INF/classes!/share/background.jpg
還是推薦第一種寫法把。
原文鏈接:https://blog.csdn.net/zombres/article/details/80896059