1. 程式人生 > 其它 >SpringBoot 之 Web 使用 Thymeleaf 模板

SpringBoot 之 Web 使用 Thymeleaf 模板

技術標籤:ThymeleafThymeleaf

一、簡介
目前 Java Web 開發推薦使用模板引擎,不建議使用 JSP 頁面
JSP缺點:本質上就是Servlet,需要後臺編譯,耗時,效率低
模板引擎:不需要編譯,速度快
常見的模板引擎:Freemarker、Velocity、Thymeleaf 等
SpringBoot 推薦使用 Thymeleaf,且預設不支援 JSP,因為 JSP 必須要打包war包才二、使用步驟
2.1、新增 Thymeleaf 依賴

<dependency>
  <groupId>org.springframework.boot<
/groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

2.2、將 HTML 頁面放到 templates 目錄中
templates 目錄下的 HTML 頁面預設不能被直接訪問,需要通過controller 來訪問,由 thymeleaf 來渲染,自動新增字首和字尾。

@RequestMapping("/test1")
public String test01(Model model){
    model.addAttribute(
"name","alice"); return "success"; }

2.3、使用Thymeleaf編寫一個 success.html

<!DOCTYPE html>
<!--匯入thymeleaf的名稱空間-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>
Title</title> </head> <body> <h2>Success!</h2> <!--使用th:text屬性,設定元素的文字,表示式${}可以獲取作用域中的屬性--> <div th:text="${name}"></div> </body> </html>

修改配置,使得頁面修改立即生效

#禁用thymeleaf的快取,使得修改頁面馬上生
spring.thymeleaf.cache=false

備註:還需要開啟IDEA的自動編譯,IDEA預設是不自動編譯
Settting——>搜尋Compiler——>Build Project Automatically
Help——>Find Action——>搜尋Registry——>勾選compiler.automake…
2.4、測試結果
開啟瀏覽器,在瀏覽器位址列中輸入:
http://localhost:8082/test1 ,檢視結果如下:

在這裡插入圖片描述
三、語法規則
3.1、常用屬性
• th:text、th:utext 設定元素中的文字內容 th:text對特殊字元進行轉義,等價於內聯方式[[ ] ] t h : u t e x t 對 特 殊 字 符 不 進 行 轉 義 , 等 價 於 內 聯 方 式 [ ( { }]] th:utext對特殊字元不進行轉義,等價於內聯方式[( ]]th:utext[({ })]
• th:html原生屬性 用來替換指定的html原生屬性的值
• th:if、th:unless、th:switch、th:case 條件判斷,類似於c:if
• th:each 迴圈,類似於c:forEach
• th:object、th:field 用於表單資料物件的繫結,將表單繫結到Controller的一個JavaBean引數,常與th:field一起使用 需要和*{}選擇表示式配合使用
• th:fragment 宣告程式碼片段,常用於頁面頭部和尾部的引入
• th:include、th:insert、th:replace 引入程式碼片段,類似於jsp:include 三者的區別:
th:include 保留自己的標籤,不要th:frament的標籤(Thymeleaf 3.0中不推薦使用)
th:insert 保留自己的標籤,保留th:frament的標籤
th:replace 不要自己的標籤,保留th:frament的標籤
3.2、表示式
• ${} 變量表達式 獲取物件的屬性、方法 使用內建的基本物件,如session、application等 使用內建的工具物件,如#strings、#dates、#arrays、#lists、#maps等
• *{}選擇表示式(星號表示式) 需要和th:object配合使用,簡化獲取物件的屬性
• @{} url表示式 定義url
• 運算子 eq gt le == != 三目運算子

四、用例示範
4.1、編寫相關 HTML 頁面
定義兩個片段 footer.html 和 header.html,每個頁面都可以引用

<!--定義 footer.html-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
    <!--th:fragment-->
    <footer th:fragment="copy">
        這是頁面的底部,版權
    </footer>
</body>
</html>

<!--定義header.html-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
    <!--th:fragment-->
    <header th:fragment="head">
        這是頁面的頭部,導航
    </header>
</body>
</html>

編寫 result.html 頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--th:text ;th:utext-->
    <div th:text="${hello}">aaa</div>
    <div th:utext="${hello}">bbb</div>
    <!--使用內聯的方式,可以再文字的前後新增內容-->
    <div>[[${hello}]]aaa</div>
    <div>[(${hello})]bbb</div>

    <!--th:html 原生屬性-->
    <div id="div1" title="這是一個div" th:id="${id}" th:title="${title}"></div>

    <!--th:if、th:unless、th:switch/th:case-->
     <!--if判斷-->
    <p th:if="${age > 18}">成年</p>

    <!--if相反的判斷-->
    <p th:unless="${age < 18}">成年</p>

    <!--th:switch switch條件判斷-->
    <p th:switch="${role}">
        <span th:case="admin">管理員</span>
        <span th:case="teacher">老師</span>
        <span th:case="student">學生</span>
        <span th:case="*">其他</span>
    </p>

    <!--th:each 迴圈-->
    <ul>
        <li th:each="name:${names}" th:text="${name}"></li>
        <!--內聯的方式-->
        <li th:each="name:${names}">[[${name}]]</li>
    </ul>

    <!--th:object th:field 用於表單資料物件的繫結,將繫結到controller的一個javaBean引數,常與th:field一起使用-->
    <!--需要和 *{} 選擇表示式配合使用-->
    <h3>修改使用者資訊</h3>
    <form action="modify" method="post" th:object="${user}">
        編號:<input type="text" th:field="*{id}" readonly><br>
        姓名:<input type="text" th:field="*{name}"><br>
        年齡:<input type="text" th:field="*{age}"><br>
        <input type="submit" value="修改">
    </form>

    <!--th:fragment 用來宣告程式碼片段,常用於頁面頭部和尾部的引入-->
    <!--th:include 引入程式碼片段,th:insert th:replace-->
    <!--表示需要去引入include下面的header.html中的fragment=head的程式碼片段-->
    <div th:include="include/header::head"></div>
    <div th:insert="include/footer::copy"></div>
    <div th:replace="include/header::head"></div>
</body>
</html>


編寫 list.html 頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入 css-->
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <!--獲取物件的屬性和方法-->
    <div th:text="${person.name}"></div>
    <div th:text="${person['age']}"></div>
    <div th:text="${persons[1].name}"></div>
    <div th:text="${persons.size()}"></div>
    <div>元素的個數:[[${persons.size()}]]</div>
    <div th:text="${persons.get(2).name}"></div>
    <hr>
    <!--使用內建的基本物件-->
    <div th:text="${session.sex}"></div>
    <div th:text="${application.hobby}"></div>
    <hr>
    <!--使用內建的工具物件-->
    <div th:text="${#strings.startsWith(person.name,'s')}"></div>
    <div th:text="${#strings.substring(person.name,1,2)}"></div>
    <div th:text="${#strings.length(person.name)}"></div>
    <div th:text="${#dates.createNow()}"></div>
    <div th:text="${#dates.create(2019,2,14)}"></div>
    <div th:text="${#dates.format(birthday,'yyyy-MM-dd HH:mm:ss')}"></div>
    <hr>
    <!--通過基本物件獲取物件屬性值-->
    <div th:text="${person.id}"></div>
    <div th:text="${person.name}"></div>
    <div th:text="${person.age}"></div>
    <hr>
    <!--*{}選擇表示式 來獲取物件值-->
    <div th:object="${person}">
        <div th:text="*{id}"></div>
        <div th:text="*{name}"></div>
        <div th:text="*{age}"></div>
    </div>

    <hr>
      <!--@{} url表示式-->
    <a href="#" th:href="@{/findUser(username=${person.name})}">查詢使用者資訊</a><br>
    <a href="product/list.html" th:href="@{/product/list}">商品列表</a>

    <hr>

    <!--引入js-->
    <script th:src="@{/js/common.js}"></script>
    <hr>

    <!--運算子-->
    性別:<input type="radio" name="sex" value="male" th:checked="${session.sex eq 'male'}"><input type="radio" name="sex" value="female" th:checked="${session.sex eq 'female'}"><div th:if="${address == null}">未找到地址資訊</div>

    <div th:text="${persons.size() >= 2 ? '大於等於2個' : '小於2個'}"></div>
</body>
</html>