springboot的thymeleaf解析html模板錯誤AND Thymeleaf表達式簡單使用

下面出現錯誤的代碼:

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>

關於Thymeleaf標籤的簡單使用和屬性:

LINK: https://www.cnblogs.com/beyrl-blog/p/6633182.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章