13.SpringBoot配置Thymeleaf

作者: admin | 创建时间: 2025-02-10 10:50:03 文章分类: java框架

文章简介: Thymeleaf是一个java类库,他是一个优秀的、面向Java 的xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层,具有丰富的标签语言和函数。因此,在使用Spring Boot 框架进行页面设计时, 一般都会选择Thymeleaf 模板。

简介:

Thymeleaf 是一个用于开发 Web 和独立环境项目的服务器端 Java 模板引擎。它能够处理 HTML、XML、JavaScript、CSS 甚至纯文本,在 Spring Boot 等 Java Web 开发中应用广泛。

主要特点

  1. 自然模板:Thymeleaf 支持自然模板,这意味着模板文件本身就是有效的 HTML 文件,可以在浏览器中直接打开查看静态效果,无需服务器支持。在开发过程中,前端开发人员可以专注于页面设计,而后端开发人员可以在模板中添加动态内容。
  2. 与 Spring 集成良好:Thymeleaf 对 Spring 框架提供了强大的支持,能与 Spring MVC 无缝集成,方便在 Spring Boot 项目中使用。通过 Spring 的依赖注入等特性,可以轻松实现数据绑定、表单处理等功能。
  3. 丰富的标签和表达式:Thymeleaf 提供了一系列自定义的标签和表达式,用于在模板中处理动态内容。例如,使用 th:text 标签可以将模型中的数据显示在 HTML 页面上,使用 th:if、th:each 等标签可以实现条件判断和循环遍历。
  4. 多语言支持:Thymeleaf 支持国际化和本地化,可以根据用户的语言环境显示不同的文本内容,方便开发多语言的 Web 应用。

基本用法(在 Spring Boot 项目中)

1. 添加依赖

在 pom.xml 中添加 Thymeleaf 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 创建 Thymeleaf 模板文件

在 src/main/resources/templates 目录下创建 HTML 模板文件,例如 hello.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello Thymeleaf</title>
</head>
<body>
    <h1 th:text="${message}">Default Message</h1>
</body>
</html>

在上述代码中,xmlns:th="http://www.thymeleaf.org" 声明了 Thymeleaf 的命名空间,th:text="${message}" 表示将模型中的 message 属性值显示在 h1 标签中。

3. 创建控制器

创建一个控制器类,将数据传递给 Thymeleaf 模板:

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 hello(Model model) {
        model.addAttribute("message", "Hello, Thymeleaf!");
        return "hello";
    }
}

在这个控制器中,@GetMapping("/hello") 注解表示处理 /hello 请求,model.addAttribute("message", "Hello, Thymeleaf!") 将数据添加到模型中,return "hello" 表示返回 hello.html 模板。

4. 运行项目

启动 Spring Boot 项目,访问 http://localhost:8080/hello,就可以看到页面上显示 “Hello, Thymeleaf!”。

常用标签和表达式

常用标签

  • th:text:用于显示文本内容,将模型中的数据替换到 HTML 标签中。
  • th:each:用于循环遍历集合或数组,例如:
<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>
  • th:if 和 th:unless:用于条件判断,例如:
<p th:if="${condition}">This paragraph will be displayed if the condition is true.</p>
<p th:unless="${condition}">This paragraph will be displayed if the condition is false.</p>

常用表达式

  • ${...}:变量表达式,用于访问模型中的属性,如 ${message}。
  • *{...}:选择变量表达式,用于访问当前选择对象的属性,通常在表单处理中使用。
  • #{...}:消息表达式,用于国际化消息的处理。

总结

Thymeleaf 是一个功能强大、易于使用的 Java 模板引擎,通过自然模板、丰富的标签和表达式以及与 Spring 框架的良好集成,能够帮助开发人员高效地开发 Web 应用。

评论

目录

    关闭