首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Thymeleaf- Spring - Boot中一个接一个地迭代?

在Thymeleaf-Spring-Boot中,可以使用Thymeleaf的迭代器来实现一个接一个地迭代。具体步骤如下:

  1. 在Spring Boot项目中引入Thymeleaf依赖。在pom.xml文件中添加以下依赖:
代码语言:txt
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 创建一个Controller类,用于处理请求和返回数据。例如,创建一个名为"UserController"的类,并添加一个方法来处理用户列表请求:
代码语言:txt
复制
@Controller
public class UserController {
    
    @GetMapping("/users")
    public String getUsers(Model model) {
        List<User> userList = // 从数据库或其他数据源获取用户列表
        model.addAttribute("users", userList);
        return "user-list";
    }
}
  1. 创建一个Thymeleaf模板文件,用于展示用户列表。在resources/templates目录下创建一个名为"user-list.html"的文件,并使用Thymeleaf语法进行迭代:
代码语言:txt
复制
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
        </tr>
    </table>
</body>
</html>
  1. 运行Spring Boot应用程序,并访问"/users"路径,即可看到用户列表页面,其中的数据会通过Thymeleaf的迭代器逐个展示出来。

在这个例子中,Thymeleaf的迭代器使用th:each属性来指定要迭代的集合,并使用th:text属性来显示每个用户的属性值。通过在Controller中将用户列表添加到Model中,然后在Thymeleaf模板中使用${users}来引用该列表,就可以实现一个接一个地迭代用户数据。

推荐的腾讯云相关产品:腾讯云云服务器(https://cloud.tencent.com/product/cvm)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券