更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞👍收藏⭐评论✍
重学SpringBoot3-集成Thymeleaf
Thymeleaf 是一个现代的服务器端Java模板引擎,用于Web和独立环境。它能够处理HTML、XML、JavaScript、CSS甚至纯文本。Thymeleaf 的主要目标是提供一个优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,这意味着你可以将静态原型直接转换成动态模板,无需更改标记。 凭借 Spring Framework 的模块、与你喜爱的工具的大量集成以及插入你自己的功能的能力,Thymeleaf 非常适合现代 HTML5 JVM Web 开发。
1. 添加Thymeleaf依赖
首先,你需要在项目的pom.xml
文件中加入Spring Boot的Thymeleaf Starter依赖。如果你使用Maven构建项目,可以添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果你使用Gradle,可以在build.gradle
文件中添加:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
2. 配置Thymeleaf属性(可选)
虽然Spring Boot的自动配置已经提供了一个合理的默认配置:
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
但你仍然可以通过 application.properties
或 application.yml
文件自定义 Thymeleaf 的一些属性。例如:
# 设置Thymeleaf模板文件的前缀位置(默认是`src/main/resources/templates`)
spring.thymeleaf.prefix=classpath:/templates/
# 设置模板文件的后缀(默认是`.html`)
spring.thymeleaf.suffix=.html
# 设置模板模式(默认是HTML5,Thymeleaf 3中为`HTML`)
spring.thymeleaf.mode=HTML
# 开启模板缓存(开发时建议关闭,生产时开启)
spring.thymeleaf.cache=false
3. 创建Thymeleaf模板
接下来,在 src/main/resources/templates
目录下创建 Thymeleaf 模板文件。例如,创建一个名为 greeting.html
的模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'">Hello, World!</h1>
</body>
</html>
4. 创建一个Controller
现在,创建一个Spring MVC Controller,用于处理用户请求并返回Thymeleaf模板视图:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GreetingController {