Thymeleaf 是一个现代的服务器端Java模板引擎,用于生成HTML、XML、JavaScript、CSS等类型的文件内容。它允许开发者通过简单的标签属性来实现复杂的逻辑,从而轻松构建动态Web页面。
在本篇文章中,我们将详细介绍如何在Java项目中集成和使用Thymeleaf模板引擎来创建动态Web页面,并提供详细的实践步骤和代码示例。
Thymeleaf 的主要特点包括:
Thymeleaf 常用于Spring框架中的MVC模式,与Spring Boot结合使用时尤其方便。
首先,我们需要创建一个Spring Boot项目。你可以通过 Spring Initializr 来快速生成项目结构。选择以下依赖项:
在 src/main/resources/application.properties
文件中,添加以下配置以启用Thymeleaf:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
接下来,我们创建一个Controller类来处理HTTP请求并返回动态页面。
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "欢迎来到Thymeleaf世界!");
return "hello";
}
}
在这个例子中,当访问 /hello
路径时,会将 message
属性传递给名为 hello.html
的模板。
在 src/main/resources/templates/
目录下创建 hello.html
文件,内容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf 示例</title>
</head>
<body>
<h1 th:text="${message}">默认消息</h1>
</body>
</html>
这里我们使用了 th:text
属性来动态设置 <h1>
标签的内容。${message}
表达式会从模型中获取 message
属性的值。
启动Spring Boot应用程序后,访问 http://localhost:8080/hello
,你将看到页面上显示“欢迎来到Thymeleaf世界!”。
Thymeleaf 支持条件判断,例如:
<div th:if="${user != null}">
欢迎您,<span th:text="${user.name}"></span>!
</div>
如果需要遍历列表数据,可以使用 th:each
属性:
<ul>
<li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>
生成动态URL可以使用 @{}
表达式:
<a th:href="@{/user/{id}(id=${userId})}">用户详情</a>
通过本文的介绍,你应该已经了解了如何在Java项目中使用Thymeleaf模板引擎来构建动态Web页面。Thymeleaf 提供了丰富的功能,能够满足大多数Web开发需求。