Spring Boot – Thymeleaf 是如何工作的?

Thymeleaf 是一个 Java 库,模板引擎用于解析应用程序生成的数据并将其呈现为模板文件 - 从而提供转换。它就像 HTML,但提供了更多用于处理渲染数据的属性。它允许缓存解析的数据/文件以提高生产时的效率。它可以处理的模板类型有 – HTML、JAVASCRIPT、CSS、XML、TEXT、RAW。

与 Spring-Boot 一起使用的模板引擎:

  1. Thymeleaf
  2. FreeMarker
  3. Mustache
  4. Groovy
  5. Java Server Pages

Thymeleaf 如何与 Spring-Boot 配合使用?

  1. Thymeleaf 遵循解耦架构——它不知道任何 Web 框架。
  2. 同样,它不知道Spring对模型的抽象,因此无法处理控制器放置在模型中的数据。
  3. 当 Spring-Boot 的自动配置在类路径中检测到 Thymeleaf 时,它会为 Spring MVC 创建支持 Thymeleaf 视图的 bean。
  4. 它可以与 Servlet 的请求属性一起使用。
  5. 因此,Spring 将模型数据复制到 Thymeleaf 模板可以使用的请求属性中。

要使用 Thymeleaf,请在项目构建中添加其依赖项。
Maven – pom.xml

<dependency>
 <groupID>org.springframework.boot</groupID>
 <artifactID>spring-boot-starter-thymeleaf</artifactID>
</dependency>


1、渲染单个模型属性
要渲染属性,请在 Thymeleaf 模板中使用 'th:text' 属性

<p th:text="${attributeKey}"> attributeValue 将放置在此处 </p>

下面展示两个步骤:
(1)、控制器(TemplateController.java)文件:

package gfg; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.RequestMapping; 

@Controller
@RequestMapping("/"
public class TemplateController { 
    
    @GetMapping(
"/template1"
    public String template(Model model) { 
        String msg =
"Welcome to Thymeleaf Template"
        
// adding the attribute(key-value pair) 
        model.addAttribute(
"message", msg); 
        
// returning the view name 
        return
"index"
    } 
}

(2)、模板(index.html)文件:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th=
"http://www.thymeleaf.org"
 <head> 
 <title>GFG</title> 
 </head> 
 <body> 
 <h1>Welcome </h1> 
 <div id=
"one"
     <h1 th:text=
"${message}"
       <span>message will print here</span> 
     </h1>  
 </div> 
 </body> 
 </html>

把上面的模板文件放在/src/main/resources/templates/

2、呈现集合
要渲染集合,请在 Thymeleaf 模板中使用 "th:each "属性

<p th:each="variable:${collectionName}"
   <span th:text=${variable}> items iterated will be placed here </span>
</p> 

(1)控制器

package gfg; 

import java.util.ArrayList; 
import java.util.List; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.RequestMapping; 

@Controller
@RequestMapping("/"
public class TemplateController2 { 
    
    @GetMapping(
"/template2"
    public String template(Model model) { 
        String message =
"Top 5 Cloud Service Providers"
        
// creating a collection 
        List<String> list = new ArrayList<>(); 
        list.add(
"Amazon Web Services"); 
        list.add(
"Microsoft Azure"); 
        list.add(
"Google Cloud"); 
        list.add(
"Alibaba Cloud"); 
        list.add(
"IBM Cloud"); 
        model.addAttribute(
"message", message); 
        
// adding the collection attribute 
        model.addAttribute(
"cloudProvider", list); 
        return
"index2"
    } 
}

(2)、模板文件 index2.html

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th=
"http://www.thymeleaf.org"
<head> 
<title>GFG2</title> 
</head> 
<body> 
<div id=
"one"
    <h2 th:text=
"${message}"
    <span>message will print here</span> 
    </h2> 
</div > 
<div id=
"two" th:each="List:${cloudProvider}"
    <ul> 
    <li> 
        <span th:text=${List}>items will print here</span> 
    </li> 
    </ul> 
</div> 
</body> 
</html>

3.将数据绑定到对象
先决条件

  • 绑定值的对象必须为每个字段提供 "getter/setter "方法。
  • 您可以使用 "Lombok "库通过"@Data "注解生成这些方法。

依赖:

<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <optional>true</optional>
</dependency>

使用 Thymeleaf,输入数据通过 "th:object "属性绑定到对象上

<form 
    method="POST" th:object="${objectName}">
</form>

要将输入映射到对象的特定字段,请使用 "th:field "属性

<input type="text" th:field="*{fieldName}" />

控制器代码:

package gfg; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.PostMapping; 
import org.springframework.web.bind.annotation.RequestMapping; 

import gfg.os.OperatingSystem; 

@Controller
@RequestMapping("/template3"
public class TemplateController3 { 
    
    @GetMapping
    public String template(Model model) { 
        model.addAttribute(
"ops", new OperatingSystem()); 
        return
"index3"
    } 
    
    @PostMapping
    public String template( @ModelAttribute(
"ops") OperatingSystem os , Model model) { 
        model.addAttribute(
"message", os.getOS1()+" "+os.getOS2()+" "+os.getOS3()); 
        return
"index"
    } 
}

绑定的数据对象:

package gfg.os; 

import lombok.Data; 

@Data
public class OperatingSystem { 
    
    public String OS1 ,OS2, OS3; 
    
}

模板html文件:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th=
"http://www.thymeleaf.org"
<head> 
<title>GFG3</title> 
</head> 
<body> 
<h1>Welcome to GeeksForGeeks...</h1> 
<form method=
"POST" th:object="${ops}"

        <div><label for=
"first">First OS</label></div> 
        <input id=
"first" type="text" th:field="*{OS1}" /> 
        
        <div><label for=
"second">Second OS</label></div> 
        <input id=
"second" type="text" th:field="*{OS2}" /> 
        
        <div><label for=
"third">Third OS</label></div> 
        <input id=
"third" type="text" th:field="*{OS3}" /> 
    
        <input type=
"submit" value="Send" /> 
    
</form> 
</body> 
</html>

注意

  • 您还可以使用 Thymeleaf 的其他属性。
  • 默认情况下启用模板缓存。
    • 您可以通过在“application.properties”文件中指定以下内容来关闭缓存。

spring.thymeleaf.cache=false