本文主要是對於spring boot中thymeleaf非常淺顯的知識進行介紹,並不深入瞭解,只接觸表面,對一些較複雜的內容也不過多描述。如文中有錯誤之處,望不吝賜教,謝謝~
一、Thymeleaf簡介
Thymeleaf是面向Web和獨立環境的現代服務器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文本等文件。
模板引擎是爲了使用戶界面與業務數據(內容)分離而產生的,它可以生成特定格式的文檔,如在web開發中的常用的html文檔。
在spring boot的開發中爲什麼不使用jsp而使用thymeleaf呢?最大的原因是因爲較高版本的spring boot不兼容jsp(通過一些特殊配置可以兼容),所以使用thymeleaf(當然還有其他選擇)。
二、Thymeleaf簡單入門
(1)新建spring boot項目
(2)引入thymeleaf依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.1.11.RELEASE</version>
</dependency>
(3)新建HelloController類
package com.example.springboot_study_demo3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
//向success.html頁面加載信息
@RequestMapping("/success")
public String success(Map<String,Object> map){
map.put("success","成功");
return "success";
}
}
(4)在resources/templates目錄下新建success.html文件
<!DOCTYPE html>
<!--thymrleaf名稱空間 xmlns:th="http:www.thymeleaf.org-->
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${success}"></div>
</body>
</html>
(5)啓動項目,然後再在瀏覽器中輸入http://localhost:8080/success,便可看到如下界面,說明成功使用thymeleaf,此時在前端頁面已成功加載信息(“成功”)。
上面這個例子很簡單,和之前的spring boot的例子差不多,唯一不同的便是引入thymeleaf依賴以及將html文件放入resources/templates目錄。需要注意的便是thymeleaf的一些語法。
三、Thymeleaf基礎語法
- th:任意屬性
改變當前屬性元素裏面的文本內容,如 th:text=“success”
- 獲取變量表達式: ${…}
獲取變量值
- 選擇表達式:*{…}
{…}與{…}獲取變量,則後續可用{…}代替這個變量
<!--官方文檔示例-->
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
- @{…}
定義url
<!--官方文檔示例-->
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
- #{…}
獲取國際化內容
- 片段引用表達式:~{…}
一般是引用html片段
2020.03.29