springboot 工程
目錄結構
├─static
├─css
└─js
└─templates
templates 模板文件目錄 thymeleaf/freemarker
springboot查找靜態資源的相關配置項:
# 應用上下文配置
server.servlet.context-path=/myprojectname
# 默認配置會自動在 /public /static /resources 目錄尋找靜態資源, 故不需要 /static 等前綴
spring.mvc.static-path-pattern=/**
# SpringMvc(ModelAndView) 視圖前綴 prefix/xxx/xxx.html, 可不設,如果static目錄下有以工程名命名的文件夾,則可以設置(如: /static/project/css)
spring.mvc.view.prefix=${server.servlet.context-path}
html 引用靜態文件
```
<link href="/myprojectname/css/bootstrap.css" rel="stylesheet">
<script src="/myprojectname/js/jquery.js">
```
靜態資源404問題總結
- 若設置 server.servlet.context-path=/myprojectname 則每個靜態資源都需要加上該值, 否則會出現404的問題
<link href="/myprojectname/css/bootstrap.css" rel="stylesheet">
- ./ 和 / 的區別
- ./ 相對路徑, 會動態匹配當前請求的路徑作為前綴(如: 若Controller 的 RequestMapping("/login")):
則實際請求路徑為 http://ip:port/login/css/bootstrap.css, 很明顯不可能每個頁面都有bootstrap.css, 所以就會出現404
(換句話說: 請求地址"http://ip:port/login/login.html", 則login.html引入的<link href="./css/bootstrap.css"> 的實際請求路徑為http://ip:port/login/css/bootstrap.css) - /url 絕對路徑: 實際請求路徑 http://ip:port/css/bootstrap.css, 若設置 server.servlet.context-path, 依然報404
如果每個 Controller 都沒有 RequestMapping 則html中可以使用 ./ , 但這樣不利用業務模塊劃分.
- ./ 相對路徑, 會動態匹配當前請求的路徑作為前綴(如: 若Controller 的 RequestMapping("/login")):