細品 Spring Boot+Thymeleaf,還有這麼多好玩的細節

TigerJin發表於2021-09-09

@[toc]
雖然現在流行前後端分離,但是後端模版在一些關鍵地方還是非常有用的,例如郵件模版、程式碼模版等。當然也不排除一些古老的專案後端依然使用動態模版。

Thymeleaf 簡潔漂亮、容易理解,並且完美支援 HTML5,可以直接開啟靜態頁面,同時不新增標籤,只需增強屬性,這樣也降低了學習成本。

因此松哥今天花點時間和大家仔細分享一下 Thymeleaf。

1. Thymeleaf 簡介

Thymeleaf 是新一代 Java 模板引擎,它類似於 Velocity、FreeMarker 等傳統 Java 模板引擎,但是與傳統 Java 模板引擎不同的是,Thymeleaf 支援 HTML 原型。

它既可以讓在瀏覽器中直接開啟檢視樣式,也可以讓後端工程師結合真實資料檢視顯示效果,同時,SpringBoot 提供了 Thymeleaf 自動化配置解決方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事實上, Thymeleaf 除了展示基本的 HTML ,進行頁面渲染之外,也可以作為一個 HTML 片段進行渲染,例如我們在做郵件傳送時,可以使用 Thymeleaf 作為郵件傳送模板。

另外,由於 Thymeleaf 模板字尾為 .html,可以直接被瀏覽器開啟,因此,預覽時非常方便。

2. 整合 Spring Boot

2.1 基本用法

Spring Boot 中整合 Thymeleaf 非常容易,只需要建立專案時新增 Thymeleaf 即可:

圖片描述

建立完成後,pom.xml 依賴如下:

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

當然,Thymeleaf 不僅僅能在 Spring Boot 中使用,也可以使用在其他地方,只不過 Spring Boot 針對 Thymeleaf 提供了一整套的自動化配置方案,這一套配置類的屬性在 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 中,部分原始碼如下:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
}
  1. 首先透過 @ConfigurationProperties 註解,將 application.properties 字首為 spring.thymeleaf 的配置和這個類中的屬性繫結。
  2. 前三個 static 變數定義了預設的編碼格式、檢視解析器的字首、字尾等。
  3. 從前三行配置中,可以看出來,Thymeleaf 模板的預設位置在 resources/templates 目錄下,預設的字尾是 html
  4. 這些配置,如果開發者不自己提供,則使用 預設的,如果自己提供,則在 application.properties 中以 spring.thymeleaf 開始相關的配置。

而我們剛剛提到的,Spring Boot 為 Thymeleaf 提供的自動化配置類,則是 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration ,部分原始碼如下:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

可以看到,在這個自動化配置類中,首先匯入 ThymeleafProperties ,然後 @ConditionalOnClass 註解表示噹噹前系統中存在 TemplateModeSpringTemplateEngine 類時,當前的自動化配置類才會生效,即只要專案中引入了 Thymeleaf 相關的依賴,這個配置就會生效。

這些預設的配置我們幾乎不需要做任何更改就可以直接使用了。如果開發者有特殊需求,則可以在 application.properties 中配置以 spring.thymeleaf 開頭的屬性即可。

接下來我們就可以建立 Controller 了,實際上引入 Thymeleaf 依賴之後,我們可以不做任何配置。新建的 IndexController 如下:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("javaboy:" + i);
            u.setAddress("深圳:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";
    }
}
public class User {
    private Long id;
    private String name;
    private String address;
    //省略 getter/setter
}

IndexController 中返回邏輯檢視名+資料,邏輯檢視名為 index ,意思我們需要在 resources/templates 目錄下提供一個名為 index.htmlThymeleaf 模板檔案。

  • 建立 Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>編號</td>
        <td>使用者名稱</td>
        <td>地址</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>
</body>
</html>

Thymeleaf 中,透過 th:each 指令來遍歷一個集合,資料的展示透過 th:text 指令來實現,

注意 index.html 最上面引入 thymeleaf 名稱空間(最新版並無強制要求)。

配置完成後,就可以啟動專案了,訪問 /index 介面,就能看到集合中的資料了:

圖片描述

2.2 手動渲染

前面我們說的是返回一個 Thymeleaf 模板,我們也可以手動渲染 Thymeleaf 模板,這個一般在郵件傳送時候有用,例如我在 resources/templates 目錄下新建一個郵件模板,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello 歡迎 <span th:text="${username}"></span>加入 XXX 集團,您的入職資訊如下:</p>
<table border="1">
    <tr>
        <td>職位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<img src="/images/sb/javaboy.jpg" alt="">
</body>
</html>

這一個 HTML 模板中,有幾個變數,我們要將這個 HTML 模板渲染成一個 String 字串,再把這個字串透過郵件傳送出去,那麼如何手動渲染呢?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
    Context context = new Context();
    context.setVariable("username", "javaboy");
    context.setVariable("position", "Java工程師");
    context.setVariable("salary", 99999);
    String mail = templateEngine.process("mail", context);
    //省略郵件傳送
}
  1. 渲染時,我們需要首先注入一個 TemplateEngine 物件,這個物件就是在 Thymeleaf 的自動化配置類中配置的(即當我們引入 Thymeleaf 的依賴之後,這個例項就有了)。
  2. 然後構造一個 Context 物件用來存放變數。
  3. 呼叫 process 方法進行渲染,該方法的返回值就是渲染後的 HTML 字串,然後我們將這個字串傳送出去。

3. Thymeleaf 細節

前面兩個案例讓小夥伴們大致上理解了在 Spring Boot 中要如何使用 Thymeleaf,接下來,松哥將詳細介紹 Thymeleaf 本身的一些具體用法。

3.1 標準表示式語法

3.1.1 簡單表示式

${...}

直接使用 th:xx = "${}" 獲取物件屬性。這個在前面的案例中已經演示過了,不再贅述。

*{...}

可以像 ${...} 一樣使用,也可以透過 th:object 獲取物件,然後使用 th:xx = "*{}" 獲取物件屬性,這種簡寫風格極為清爽,推薦大家在實際專案中使用。

<table border="1" th:object="${user}">
<tr>
    <td>使用者名稱</td>
    <td th:text="*{username}"></td>
</tr>
<tr>
    <td>地址</td>
    <td th:text="*{address}"></td>
</tr>
</table>

#{...}

通常的國際化屬性:#{...} 用於獲取國際化語言翻譯值。

在 resources 目錄下新建兩個檔案:messages.properties 和 messages_zh_CN.properties,內容如下:

messages.properties:

message = javaboy

messages_zh_CN.properties:

message = 江南一點雨

然後在 thymeleaf 中引用 message,系統會根據瀏覽器的語言環境顯示不同的值:

<div th:text="#{message}"></div>

@{...}

  • 引用絕對 URL:
<script type="text/javascript" th:src="@{}"></script>

等價於:

<script type="text/javascript" src=""></script>
  • 上下文相關的 URL:

首先在 application.properties 中配置 Spring Boot 的上下文,以便於測試:

server.servlet.context-path=/myapp

引用路徑:

<script type="text/javascript" th:src="@{/hello.js}"></script>

等價於:

<script type="text/javascript" src="/myapp/hello.js"></script>
  • 相對 URL:

這個相對是指相對於伺服器的 URL,例如如下引用:

<script type="text/javascript" th:src="@{~/hello.js}"></script>

等價於:

<script type="text/javascript" src="/hello.js"></script>

應用程式的上下文 /myapp 將被忽略。

  • 協議相對 URL:
<script type="text/javascript" th:src="@{//localhost:8080/hello.js}"></script>

等價於:

<script type="text/javascript" src="//localhost:8080/hello.js"></script>
  • 帶引數的 URL:
<script type="text/javascript" th:src="@{//localhost:8080/hello.js(name='javaboy',age=99)}"></script>

等價於:

<script type="text/javascript" th:src="//localhost:8080/hello.js?name=javaboy&age=99"></script>

~{...}

片段表示式是 Thymeleaf 的特色之一,細粒度可以達到標籤級別,這是 JSP 無法做到的。片段表示式擁有三種語法:

  • ~{ viewName }:表示引入完整頁面
  • ~{ viewName ::selector}:表示在指定頁面尋找片段,其中 selector 可為片段名、jquery選擇器等
  • ~{ ::selector}: 表示在當前頁尋找

舉個簡單例子。

在 resources/templates 目錄下新建 my_fragment.html 檔案,內容如下:

<div th:fragment="javaboy_link"><a href=""></a></div>
<div th:fragment="itboyhub_link"><a href=""></a></div>

這裡有兩個 div,透過 th:fragment 來定義片段,兩個 div 分別具有不同的名字。

然後在另外一個頁面中引用該片段:

<table border="1" th:object="${user}" th:fragment="aaa">
<tr>
    <td>使用者名稱</td>
    <td th:text="*{username}"></td>
</tr>
<tr>
    <td>地址</td>
    <td th:text="*{address}"></td>
</tr>
</table>
<hr>
<div th:replace="my_fragment.html"></div>
<hr>
<div th:replace="~{my_fragment.html::javaboy_link}"></div>
<hr>
<div th:replace="~{::aaa}"></div>

透過 th:replace 來引用片段。第一個表示引用完整的 my_fragment.html 頁面;第二個表示引用 my_fragment.html 中的名為 javaboy_link 的片段;第三個表示引用當前頁面名為 aaa 的片段,也就是上面那個 table。

3.1.2 字面量

這些是一些可以直接寫在表示式中的字元,主要有如下幾種:

  • 文字字面量: ‘one text’, ‘Another one!’,…
  • 數字字面量: 0, 34, 3.0, 12.3,…
  • 布林字面量: true, false
  • Null字面量: null
  • 字面量標記:one, sometext, main,…

案例:

<div th:text="'這是 文字字面量(有空格)'"></div>
<div th:text="javaboy"></div>
<div th:text="99"></div>
<div th:text="true"></div>

如果文字是英文,並且不包含空格、逗號等字元,可以不用加單引號。

3.1.3 文字運算

文字可以使用 + 進行拼接。

<div th:text="'hello '+'javaboy'"></div>
<div th:text="'hello '+${user.username}"></div>

如果字串中包含變數,也可以使用另一種簡單的方式,叫做字面量置換,用 | 代替 '...' + '...',如下:

<div th:text="|hello ${user.username}|"></div>
<div th:text="'hello '+${user.username}+' '+|Go ${user.address}|"></div>

3.1.4 算術運算

算術運算有:+, -, *, /%

<div th:with="age=(99*99/99+99-1)">
    <div th:text="${age}"></div>
</div>

th:with 定義了一個區域性變數 age,在其所在的 div 中可以使用該區域性變數。

3.1.5 布林運算

  • 二元運算子:and, or
  • 布林非(一元運算子):!, not

案例:

<div th:with="age=(99*99/99+99-1)">
    <div th:text="9 eq 9 or 8 ne 8"></div>
    <div th:text="!(9 eq 9 or 8 ne 8)"></div>
    <div th:text="not(9 eq 9 or 8 ne 8)"></div>
</div>

3.1.6 比較和相等

表示式裡的值可以使用 >, <, >=<= 符號比較。==!= 運算子用於檢查相等(或者不相等)。注意 XML規定 <> 標籤不能用於屬性值,所以應當把它們轉義為 &lt;&gt;

如果不想轉義,也可以使用別名:gt (>);lt (<);ge (>=);le (<=);not (!)。還有 eq (==), neq/ne (!=)。

舉例:

<div th:with="age=(99*99/99+99-1)">
    <div th:text="${age} eq 197"></div>
    <div th:text="${age} ne 197"></div>
    <div th:text="${age} ge 197"></div>
    <div th:text="${age} gt 197"></div>
    <div th:text="${age} le 197"></div>
    <div th:text="${age} lt 197"></div>
</div>

3.1.7 條件運算子

類似於我們 Java 中的三目運算子。

<div th:with="age=(99*99/99+99-1)">
    <div th:text="(${age} ne 197)?'yes':'no'"></div>
</div>

其中,: 後面的部分可以省略,如果省略了,又同時計算結果為 false 時,將返回 null。

3.1.8 內建物件

基本內建物件:

  • #ctx:上下文物件。
  • #vars: 上下文變數。
  • #locale:上下文區域設定。
  • #request:(僅在 Web 上下文中)HttpServletRequest 物件。
  • #response:(僅在 Web 上下文中)HttpServletResponse 物件。
  • #session:(僅在 Web 上下文中)HttpSession 物件。
  • #servletContext:(僅在 Web 上下文中)ServletContext 物件。

在頁面可以訪問到上面這些內建物件,舉個簡單例子:

<div th:text='${#session.getAttribute("name")}'></div>

實用內建物件:

  • #execInfo:有關正在處理的模板的資訊。
  • #messages:在變數表示式中獲取外部化訊息的方法,與使用#{…}語法獲得的方式相同。
  • #uris:轉義URL / URI部分的方法
  • #conversions:執行配置的轉換服務(如果有)的方法。
  • #dates:java.util.Date物件的方法:格式化,元件提取等
  • #calendars:類似於#dates但是java.util.Calendar物件。
  • #numbers:用於格式化數字物件的方法。
  • #strings:String物件的方法:contains,startsWith,prepending / appending等
  • #objects:一般物件的方法。
  • #bools:布林評估的方法。
  • #arrays:陣列方法。
  • #lists:列表的方法。
  • #sets:集合的方法。
  • #maps:地圖方法。
  • #aggregates:在陣列或集合上建立聚合的方法。
  • #ids:處理可能重複的id屬性的方法(例如,作為迭代的結果)。

這是一些內建物件以及工具方法,使用方式也都比較容易,如果使用的是 IntelliJ IDEA,都會自動提示物件中的方法,很方便。

舉例:

<div th:text="${#execInfo.getProcessedTemplateName()}"></div>
<div th:text="${#arrays.length(#request.getAttribute('names'))}"></div>

3.2 設定屬性值

這個是給 HTML 元素設定屬性值。可以一次設定多個,多個之間用 , 分隔開。

例如:

<img th:attr="src=@{/1.png},title=${user.username},alt=${user.username}">

會被渲染成:

<img src="/myapp/1.png" title="javaboy" alt="javaboy">

當然這種設定方法不太美觀,可讀性也不好。Thymeleaf 還支援在每一個原生的 HTML 屬性前加上 th: 字首的方式來使用動態值,像下面這樣:

<img th:src="@{/1.png}" th:alt="${user.username}" th:title="${user.username}">

這種寫法看起來更清晰一些,渲染效果和前面一致。

上面案例中的 alt 和 title 則是兩個特殊的屬性,可以一次性設定,像下面這樣:

<img th:src="@{/1.png}" th:alt-title="${user.username}">

這個等價於前文的設定。

3.3 遍歷

陣列/集合/Map/Enumeration/Iterator 等的遍歷也算是一個非常常見的需求,Thymeleaf 中透過 th:each 來實現遍歷,像下面這樣:

<table border="1">
    <tr th:each="u : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
    </tr>
</table>

users 是要遍歷的集合/陣列,u 則是集合中的單個元素。

遍歷的時候,我們可能需要獲取遍歷的狀態,Thymeleaf 也對此提供了支援:

  • index:當前的遍歷索引,從0開始。
  • count:當前的遍歷索引,從1開始。
  • size:被遍歷變數裡的元素數量。
  • current:每次遍歷的遍歷變數。
  • even/odd:當前的遍歷是偶數次還是奇數次。
  • first:當前是否為首次遍歷。
  • last:當前是否為最後一次遍歷。

u 後面的 state 表示遍歷狀態,透過遍歷狀態可以引用上面的屬性。

<table border="1">
    <tr th:each="u,state : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</table>

3.4 分支語句

只顯示奇數次的遍歷,可以使用 th:if,如下:

<table border="1">
    <tr th:each="u,state : ${users}" th:if="${state.odd}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</table>

th:if 不僅僅只接受布林值,也接受其他型別的值,例如如下值都會判定為 true:

  • 如果值是布林值,並且為 true。
  • 如果值是數字,並且不為 0。
  • 如果值是字元,並且不為 0。
  • 如果值是字串,並且不為 “false”, “off” 或者 “no”。
  • 如果值不是布林值,數字,字元或者字串。

但是如果值為 null,th:if 會求值為 false。

th:unless 的判定條件則與 th:if 完全相反。

<table border="1">
    <tr th:each="u,state : ${users}" th:unless="${state.odd}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</table>

這個顯示效果則與上面的完全相反。

當可能性比較多的時候,也可以使用 switch:

<table border="1">
    <tr th:each="u,state : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
        <td th:switch="${state.odd}">
            <span th:case="true">odd</span>
            <span th:case="*">even</span>
        </td>
    </tr>
</table>

th:case="*" 則表示預設選項。

3.5 本地變數

這個我們前面已經涉及到了,使用 th:with 可以定義一個本地變數。

3.6 內聯

我們可以使用屬性將資料放入頁面模版中,但是很多時候,內聯的方式看起來更加直觀一些,像下面這樣:

<div>hello [[${user.username}]]</div>

用內聯的方式去做拼接也顯得更加自然。

[[...]] 對應於 th:text (結果會是轉義的 HTML),[(...)]對應於 th:utext,它不會執行任何的 HTML 轉義。

像下面這樣:

<div th:with="str='hello <strong>javaboy</strong>'">
    <div>[[${str}]]</div>
    <div>[(${str})]</div>
</div>

最終的顯示效果如下:

圖片描述

不過內聯方式有一個問題。我們使用 Thymeleaf 的一大優勢在於不用動態渲染就可以直接在瀏覽器中看到顯示效果,當我們使用屬性配置的時候確實是這樣,但是如果我們使用內聯的方式,各種表示式就會直接展示在靜態網頁中。

也可以在 js 或者 css 中使用內聯,以 js 為例,使用方式如下:

<script th:inline="javascript">
    var username=[[${user.username}]]
    console.log(username)
</script>

js 中需要透過 th:inline="javascript" 開啟內聯。

4. 小結

好啦,Thymeleaf 跟大家也介紹的差不多了,應付日常的工作應該是可以了。對 Thymeleaf 感興趣的小夥伴。

需求文件地址:gitee.com/lenve/javadoc

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2144/viewspace-2826704/,如需轉載,請註明出處,否則將追究法律責任。

相關文章