在使用springboot 和thtmeleaf開發時引用靜態資源404,靜態資源結以下:css
index.html文件:html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset = "UFT-8" /> <title>Spring Boot Application</title> <link href="css/style.css" rel="stylesheet"> <!--<link th:href="@{css/style.css}" rel="stylesheet">--> </head> <body> <h4>Welcome to Thymeleaf Spring Boot web application 亂碼亂碼</h4> <p th:text="${hello}">hello</p> <p th:text="${hi}">hi</p> <input type="text" /> </body> </html>
style.css文件web
h4 { color: red; } p { color: blue; }
測試訪問urlspring
@Controller @RequestMapping(value = "thymeleaf") public class IndexController { @RequestMapping(value = "index") public String index(Model model, ModelMap modelMap) { model.addAttribute("hello", "thymeleaf"); modelMap.addAttribute("hi", "thymeleaf"); return "index"; } @RequestMapping(value = "hello") public String hello(ModelMap modelMap) { modelMap.put("hei", "thymeleaf"); return "hello"; } }
配置文件applicationspringboot
#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode=HTML
啓動項目後訪問http://127.0.0.1:8080/thymeleaf/index,寫入的樣式並未引進項目中,打開控制檯發現靜態資源訪問的url上加上了後臺請求url的除去最後覺得的字符串(若是是/thymeleaf/index/hello將會是http://127.0.0.1:8080/thymeleaf/index/css/style.css),顯然這並非靜態資源訪問位置,404也就正常了。app
而直接訪問http://127.0.0.1:8080/css/style.css是ok的。測試
這個問題就是英文引入靜態資源文件的路徑寫的不對,index.html中的引入應該寫成url
<link href="/css/style.css" rel="stylesheet"> <!--<link th:href="@{/css/style.css}" rel="stylesheet">-->
加上「/」表示絕對路徑spa