一、敘述
spring boot 由於是內置的tomcat ,因此其在獨立運行的時候,是不需要單獨安裝 tomcat,這使其前端文件(CSS、JS、html)等放置的位置與war中的不同。
二、常見配置
要求:服務器上已經安裝過 jdk
將 靜態文件放置到 spring boot 工程下的 src/main/resources/static目錄下,html 等文件放置到 src/main/resources/templates 下,運行 main函數。目錄結構如下:
其中 含有main 的函數為:TradingSystemApplication.java. 此時運行該函數,服務啟動,打開瀏覽訪問,可正常訪問網頁。
在Springboot中默認的靜態資源路徑有:classpath:/META-INF/resources/
,classpath:/resources/
,classpath:/static/
,classpath:/public/
,經過測試發現 該classpath僅指spring boot 包中的 classes目錄:
spring boot 完整 jar 中目錄結構如下:
三、特殊要求
(1) 能夠訪問與 jar 包同級的靜態文件
實現該種功能,主要有以下幾種方式:
- 修改application.properties文件
配置如下:
spring.mvc.static-path-pattern=/** #file:css/ 表示包含該jar包的下面的目錄 spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\ file:css/,classpath:/static/,classpath:/public/
file:css/ 在工程中運行時是指:<工程根目錄>/css/;
獨立 jar 中運行的時候是指:<包含jar包目錄>/css/;
此時 spring boot 會在css 目錄下進行匹配,如訪問的靜態文件為:http://localhost:8080/context/css/hello.js ,那么 file:css/ 具體目錄下就應該有 css/hello.js 文件,目錄結構就是:.../css/css/hello.js。
- 啟動 jar 包時使用 -Dloader.path 命令指定
獨立 jar 包運行的時候,目錄結構如下:
輸入的命令如下:
java -Dloader.path=css -jar 2.jar
正常啟動之后,打開瀏覽器進行訪問,網頁顯示正常;
此時 spring boot 會在css 目錄下進行匹配,如訪問的靜態文件為:http://localhost:8080/context/css/hello.js ,那么 具體目錄下就應該有 css/hello.js 文件,目錄結構就是:.../css/css/hello.js。
(2) 能夠訪問系統中某一具體目錄下的靜態文件
修改application.properties文件
配置內容如下:
#配置靜態文件訪問地址 casslocation=E:/Program Files/develop/Git/repository/TradingSystem/test spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\ classpath:/static/,classpath:/public/,file:${casslocation}
將css及其下的目錄放入 E:/Program Files/develop/Git/repository/TradingSystem/test 目錄下,運行 含有main 函數的類,服務啟動,打開瀏覽,網頁正常顯示。
此時 spring boot 會在test 目錄下進行匹配,如訪問的靜態文件為:http://localhost:8080/context/css/hello.js ,那么 具體目錄下就應該有 css/hello.js 文件,目錄結構就是: ../test/css/hello.js。