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 模板的简单生命周期

要使用 Thymeleaf,请在项目构建中添加其依赖项。

maven-pom.xml

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

Gradle – build.gradle

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

将模板文件放在以下目录中:

/src/main/resources/templates/

项目结构(Maven)

1. 渲染单个模型属性

要呈现属性,请在 Thymeleaf 模板中使用 'th:text' 属性

<p th:text="${attributeKey}"> attributeValue will be placed here </p>

控制器(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";
	}
}

模板 (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 to GeeksForGeeks...</h1>
<div id="one">
	<h1 th:text="${message}">
	<span>message will print here</span>
	</h1>
</div>
</body>
</html>

输出:

2. 渲染集合

要呈现集合,请在 Thymeleaf 模板中使用“th:each”属性

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

注意: span 标签将与集合项的数量一样多地迭代。

控制器(TemplateController2.java)文件:

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";
	}
}

模板 (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”注释生成这些方法。

添加 Lombok 的依赖项:Maven (pom.xml)

<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}" />

控制器(TemplateController3.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.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";
	}
}

待绑定对象的类(OperatingSystem.java)文件:

package gfg.os;

import lombok.Data;

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

模板 (index3.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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值