Thymeleaf模板在Spring Boot中如何进行数据绑定

1949idc 2年前 (2024-09-18) 阅读数 308 #编程语言

在 Spring Boot 中,使用 Thymeleaf 模板进行数据绑定主要包括以下几个步骤:

  1. 添加依赖

首先,确保你的项目中已经添加了 Thymeleaf 和 Spring Boot 相关的依赖。在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 创建 Controller

创建一个 Controller 类,用于处理 HTTP 请求并返回 Thymeleaf 模板。例如,创建一个名为 UserController 的类:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @PostMapping("/submit")
    public String submitForm(@ModelAttribute User user) {
        // 处理提交的数据,例如保存到数据库
        System.out.println("User: " + user);
        return "userResult";
    }
}
  1. 创建实体类

创建一个实体类,例如 User,用于存储表单数据:

public class User {
    private String name;
    private int age;

    // getter 和 setter 方法
    // ...

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  1. 创建 Thymeleaf 模板

src/main/resources/templates 目录下创建两个 Thymeleaf 模板文件:userForm.htmluserResult.html

userForm.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Form</title>
</head>
<body>
    <h1>User Form</h1>
    <form action="#" th:action="@{/user/submit}" th:object="${user}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" th:field="*{name}" />
        <br/>
        <label for="age">Age:</label>
        <input type="number" id="age" th:field="*{age}" />
        <br/>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

userResult.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Result</title>
</head>
<body>
    <h1>User Result</h1>
    <p th:text="'Name: ' + ${user.name}"></p>
    <p th:text="'Age: ' + ${user.age}"></p>
</body>
</html>
  1. 运行应用程序

运行你的 Spring Boot 应用程序,然后访问 http://localhost:8080/user/form,你将看到一个表单,可以输入用户信息。提交表单后,将显示用户信息。这就是在 Spring Boot 中使用 Thymeleaf 模板进行数据绑定的基本过程。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业