重学SpringBoot3-集成Thymeleaf

更多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

Thymeleaf自动配置类

但你仍然可以通过 application.propertiesapplication.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 {
   
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CoderJia_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值