知識庫 / Spring / Spring MVC RSS 訂閱

Thymeleaf 在 Spring 中的使用入門

Spring MVC
HongKong
10
02:51 PM · Dec 06 ,2025

1. 概述

Thymeleaf 是一款用於處理和創建 HTML、XML、JavaScript、CSS 和文本的 Java 模板引擎。

在本教程中,我們將討論 如何使用 Thymeleaf 與 Spring 結合,以及在 Spring MVC 應用程序的視圖層中的一些基本用例。

該庫具有極強的可擴展性,其自然模板化能力確保我們可以在沒有後端的情況下快速原型化模板。相比於其他流行的模板引擎,如 JSP,這使得開發速度更快。

2. 使用 Thymeleaf 與 Spring 集成

首先,讓我們看看與 Spring 集成所需的配置。<em>thymeleaf-spring</em> 庫對於集成是必需的。

我們將以下依賴添加到我們的 Maven POM 文件中:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

請注意,對於 Spring 4 項目,我們必須使用 thymeleaf-spring4 庫,而不是 thymeleaf-spring5

SpringTemplateEngine 類執行了所有配置步驟。

我們可以將其配置為 Java 配置文件的 Bean。

@Bean
@Description("Thymeleaf Template Resolver")
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");

    return templateResolver;
}

@Bean
@Description("Thymeleaf Template Engine")
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setTemplateEngineMessageSource(messageSource());
    return templateEngine;
}

templateResolver Bean 的 prefixsuffix 屬性指示了 view 頁面在 webapp 目錄中的位置以及它們的文件擴展名,分別。

Spring MVC 中的 ViewResolver 接口將控制器返回的 view 名稱映射到實際的 view 對象。 ThymeleafViewResolver 實現 ViewResolver 接口,並用於確定給定 view 名稱時應渲染的 Thymeleaf view。

集成最後一步是添加 ThymeleafViewResolver 作為 Bean:

@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}

3. Thymeleaf 在 Spring Boot 中的使用

Spring Boot 通過添加 spring-boot-starter-thymeleaf 依賴項,為 Thymeleaf 提供自動配置。

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

無需進行任何顯式配置。默認情況下,HTML文件應放置在 resources/templates 目錄下。

4. 從消息源(屬性文件)顯示值

我們可以使用 標籤屬性來顯示屬性文件中值。

為了使這部分代碼生效,我們需要將屬性文件配置為 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 標籤屬性生效的 ```python def SpearmanCorrelation(x, y): """ Calculates the Spearman rank correlation coefficient between two arrays. Args: x: The first array. y: The second array. Returns: The Spearman rank correlation coefficient. """ import numpy as np x = np.array(x) y = np.array(y) n = len(x) if n != len(y): raise ValueError("Arrays must be of the same length") rank_x = np.argsort(np.argsort(x)) + 1 rank_y = np.argsort(np.argsort(y)) + 1 d = rank_x - rank_y d_squared = d**2 sum_d_squared = np.sum(d_squared) correlation = 1 - (6 * sum_d_squared) / (n * (n**2 - 1)) return correlation

@Bean
@Description("Spring Message Resolver")
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}

以下是使用 Thymeleaf HTML 代碼顯示與鍵 welcome.message 關聯的值:

<span th:text="#{welcome.message}" />

5. 顯示模型屬性

This section describes how to display the attributes of a model object. This is crucial for providing users with a clear understanding of the data represented by the model.

The primary method for displaying model attributes is through a custom rendering function. This function receives the model object as input and returns an HTML string representing the attributes in a user-friendly format.

Here's an example of a rendering function:

<p><strong>Name:</strong> {{ model.name }}</p>
<p><strong>Value:</strong> {{ model.value }}</p>
<p><strong>Timestamp:</strong> {{ model.timestamp }}</p>

In this example, {{ model.name }}, {{ model.value }}, and {{ model.timestamp }} are template variables that will be replaced with the corresponding values from the model object. The template engine handles the substitution process, ensuring that the values are correctly formatted and displayed.

5.1. 簡單屬性

我們可以使用 `<em th:text="${attributename}” 標籤屬性來顯示模型屬性的值。

讓我們在控制器類中添加一個名為 `<em serverTime 的模型屬性:

model.addAttribute("serverTime", dateFormat.format(new Date()));

以下是用於顯示 serverTime 屬性值的 HTML 代碼:

Current time is <span th:text="${serverTime}" />

5.2. 收集屬性

如果模型屬性是一個對象的集合,則可以使用 <em th:each</em> 屬性迭代遍歷它。

讓我們定義一個 <em Student</em> 模型類,其中包含兩個字段:<em id</em><em name</em>

public class Student implements Serializable {
    private Integer id;
    private String name;
    // standard getters and setters
}

現在我們將創建一個學生列表作為控制器類中的模型屬性:

List<Student> students = new ArrayList<Student>();
// logic to build student data
model.addAttribute("students", students);

最後,我們可以使用 Thymeleaf 模板代碼來遍歷學生列表並顯示所有字段值:

<tbody>
    <tr th:each="student: ${students}">
        <td th:text="${student.id}" />
        <td th:text="${student.name}" />
    </tr>
</tbody>

6. 條件評估

在評估過程中,系統會根據預定義的條件進行判斷。這些條件可以基於多種因素,例如數據值、用户輸入、系統狀態等。當滿足某個或多個條件時,系統會執行相應的操作或返回特定的結果。 這種機制允許系統根據不同的情況做出靈活的響應,從而實現更智能和適應性的行為。

6.1. <em if=”${condition}”</em><em unless=”${condition}”</em>

我們使用 <em if=”${condition}”</em> 屬性來顯示視圖中的一段內容,如果條件滿足。我們使用 <em unless=”${condition}”</em> 屬性來顯示視圖中的一段內容,如果條件不滿足。

讓我們為 Student 模型添加一個 gender 字段:

public class Student implements Serializable {
    private Integer id;
    private String name;
    private Character gender;
    
    // standard getters and setters
}

假設此字段有兩個可能的值(M 或 F),用於指示學生的性別。

如果我們希望顯示“Male”或“Female”而不是單個字符,可以使用以下 Thymeleaf 代碼實現:

<td>
    <span th:if="${student.gender} == 'M'" th:text="Male" /> 
    <span th:unless="${student.gender} == 'M'" th:text="Female" />
</td>

6.2. <em th:switch="expression"><em th:case="value">

我們使用 <em th:switch="expression"><em th:case="value"> 屬性來條件顯示內容,利用 switch 語句結構。

讓我們使用 <em th:switch="expression"><em th:case="value"> 屬性重寫之前的代碼:

<td th:switch="${student.gender}">
    <span th:case="'M'" th:text="Male" /> 
    <span th:case="'F'" th:text="Female" />
</td>

7. 處理用户輸入

我們可以使用 屬性來處理表單輸入。我們使用 提供表單操作 URL,使用 指定提交的表單數據將綁定到的對象。

單個字段使用 屬性進行映射,其中 是對象中匹配的屬性。

對於 類,我們可以創建一個輸入表單:

<form action="#" th:action="@{/saveStudent}" th:object="${student}" method="post">
    <table border="1">
        <tr>
            <td><label th:text="#{msg.id}" /></td>
            <td><input type="number" th:field="*{id}" /></td>
        </tr>
        <tr>
            <td><label th:text="#{msg.name}" /></td>
            <td><input type="text" th:field="*{name}" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>

在上述代碼中,/saveStudent 是表單的 action URL,student 是存儲提交的表單數據的對象。

saveStudent 方法處理表單提交:

@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
public String saveStudent(Model model, @ModelAttribute("student") Student student) {
    // logic to process input data
}

@RequestMapping 註解將控制器方法映射到提供的 URL 上。標註的方法 saveStudent() 執行提交表單所需的處理。最後,@ModelAttribute 註解將表單字段綁定到 student 對象。

8. 顯示驗證錯誤

我們可以使用 #fields.hasErrors() 函數來檢查字段是否存在任何驗證錯誤。 並且我們使用 #fields.errors() 函數來顯示特定字段的錯誤。 字段名稱是這兩個函數的輸入參數。

下面是迭代併為表單中的每個字段顯示錯誤的 HTML 代碼示例:

<ul>
    <li th:each="err : ${#fields.errors('id')}" th:text="${err}" />
    <li th:each="err : ${#fields.errors('name')}" th:text="${err}" />
</ul>

與其使用字段名稱,上述函數接受通配符 * 或常量 all 來指示所有字段。我們使用 th:each 屬性來迭代每個字段可能存在的多個錯誤。

以下是以前的 HTML 代碼,使用通配符 * 重新編寫:

<ul>
    <li th:each="err : ${#fields.errors('*')}" th:text="${err}" />
</ul>

在這裏,我們使用了常量 all

<ul>
    <li th:each="err : ${#fields.errors('all')}" th:text="${err}" />
</ul>

同樣,我們也可以使用 global 常量來顯示 Spring 全局錯誤。

以下是顯示全局錯誤的 HTML 代碼:

<ul>
    <li th:each="err : ${#fields.errors('global')}" th:text="${err}" />
</ul>

此外,我們還可以使用 屬性來顯示錯誤消息。

使用 屬性重寫用於在表單中顯示錯誤的先前代碼。

<ul>
    <li th:errors="*{id}" />
    <li th:errors="*{name}" />
</ul>

9. 使用轉換

我們使用雙括號語法 <em id="conversion_9_using_conversions_1">{{}}</em> 來格式化數據以供顯示。 這利用了上下文文件中 <em id="conversion_9_using_conversions_2">conversionService</em> bean 中針對該字段配置的 <em id="conversion_9_using_conversions_3">formatters</em>

讓我們看看如何格式化 <em id="conversion_9_using_conversions_4">Student</em> 類中的“姓名”字段:

<tr th:each="student: ${students}">
    <td th:text="${{student.name}}" />
</tr>

上述代碼使用了 NameFormatter 類,通過覆蓋 WebMvcConfigurer 接口中的 addFormatters() 方法進行配置。

為此目的,我們的 @Configuration 類覆蓋了 WebMvcConfigurerAdapter 類。

@Configuration
public class WebMVCConfig extends WebMvcConfigurerAdapter {
    // ...
    @Override
    @Description("Custom Conversion Service")
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new NameFormatter());
    }
}

NameFormatter 類實現了 Spring 的 Formatter 接口。

我們還可以使用 #conversions 工具來將對象轉換為顯示格式。該工具函數的語法是 #conversions.convert(Object, Class),其中 Object 被轉換為 Class 類型。

以下是如何使用 student 對象的 percentage 字段,並去除小數部分的示例:

<tr th:each="student: ${students}">
    <td th:text="${#conversions.convert(student.percentage, 'Integer')}" />
</tr>

10. 結論

在本文中,我們學習瞭如何在 Spring MVC 應用程序中集成和使用 Thymeleaf。

我們還看到了如何顯示字段、接受輸入、顯示驗證錯誤以及轉換數據以供顯示的方法。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.