Springboot 加載靜態資源 404問題

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 則html中可以使用 ./ , 但這樣不利用業務模塊劃分.

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容