下面出現錯誤的代碼:
java代碼:
@Controller
@RequestMapping("/sample/")
public class SampleController {
@RequestMapping("/thymeleaf")
public String thymeleaf(){
// model.addAttribute("name","dada");
return "hello";
}
}
html代碼:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" http-equiv="Content-Type">
<title>hello</title>
</head>
<body>
<p th:text="hello">"hello" +${name}</p>
</body>
</html>
application.properties配置代碼:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
運行後發現瀏覽器報無法解析hello模板,後面在下面的這兩篇文章找到了原因
LINK: https://blog.csdn.net/aixp88/article/details/72848332
LINK: https://blog.csdn.net/chaofansea/article/details/79042635
springboot默認使用 Thymeleaf 2.X版本,這個版本無法識別html5中常見的自閉合標籤
就是這段html代碼沒有使用 ''/'' 關閉標籤:
<meta charset="UTF-8" http-equiv="Content-Type">
三種解決方案:
1.嚴格按照thymeleaf 2.X 版本的編寫html (不建議)
2.使用thymeleaf 3.X 版本,在pom.xml文件加入以下代碼
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
然後在application.properties中添加以下一句:
spring.thymeleaf.mode: HTML
3.在application.properties中增加:
spring.thymeleaf.content-type=text/html
# 開發環境中關閉緩存便於測試
spring.thymeleaf.cache=false
spring.thymeleaf.mode =LEGACYHTML5
並在pom.xml中添加依賴nekoHTML 1.9.15 or newer
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>