Thymeleaf 分页实现 - 使用 Spring MVC 构建动态页面
{/'title/':/'Thymeleaf 分页实现 - 使用 Spring MVC 构建动态页面/',/'description/':/'Thymeleaf 是一个现代化的服务器端 Java 模板引擎,可用于 Web 和独立环境。本文介绍如何通过 Thymeleaf 和 Spring MVC 实现分页功能,并提供示例代码。/',/'keywords/':/'Thymeleaf, 分页, Spring MVC, Java 模板引擎, Web 开发, 动态页面/',/'content/':/'Thymeleaf 是一个用于 Web 和独立环境的现代化服务器端 Java 模板引擎,它可以与 Spring MVC 等 Web 框架集成使用。要实现分页,可以通过 Thymeleaf 结合 Spring MVC 的方式来实现。//n//n下面是一个简单的示例代码,演示如何在 Thymeleaf 中实现分页://n//n1. 首先,在控制器中注入一个分页对象和数据列表://n//njava//n@Controller//npublic class UserController {//n//n @Autowired//n private UserService userService;//n//n @GetMapping(/'/users/')//n public String getUsers(@RequestParam(defaultValue = /'0/') int page, Model model) {//n Page<User> userPage = userService.getUsers(page, 10); // 每页显示 10 条数据//n model.addAttribute(/'users/', userPage.getContent());//n model.addAttribute(/'currentPage/', page);//n model.addAttribute(/'totalPages/', userPage.getTotalPages());//n return /'users/';//n }//n}//n//n//n2. 在 Thymeleaf 模板中,使用 Thymeleaf 的迭代器来遍历用户列表,并显示分页链接://n//nhtml//n<!DOCTYPE html>//n<html xmlns:th=/'http://www.thymeleaf.org/'>//n<head>//n <title>User List</title>//n</head>//n<body>//n <h1>User List</h1>//n <table>//n <tr>//n <th>ID</th>//n <th>Name</th>//n <th>Email</th>//n </tr>//n <tr th:each=/'user : ${users}/'>//n <td th:text=/'${user.id}/'>ID</td>//n <td th:text=/'${user.name}/'>Name</td>//n <td th:text=/'${user.email}/'>Email</td>//n </tr>//n </table>//n <div>//n <a th:href=/'@{/users?page=0}/' th:if=/'${currentPage > 0}/'>First</a>//n <a th:href=/'@{/users?page=${currentPage - 1}}/' th:if=/'${currentPage > 0}/'>Previous</a>//n <span th:text=/'${currentPage} + 1/'></span>//n <a th:href=/'@{/users?page=${currentPage + 1}}/' th:if=/'${currentPage + 1 < totalPages}/'>Next</a>//n <a th:href=/'@{/users?page=${totalPages - 1}}/' th:if=/'${currentPage + 1 < totalPages}/'>Last</a>//n </div>//n</body>//n</html>//n//n//n在上述示例中,我们通过 Thymeleaf 的迭代器 th:each 来遍历用户列表,并使用 th:text 来显示用户的属性值。分页链接通过 Thymeleaf 的条件语句 th:if 来根据当前页码和总页数进行显示和隐藏。//n//n这样,当访问 /users 页面时,控制器会根据请求的页码获取相应的用户列表,并将数据传递给 Thymeleaf 模板进行渲染,同时渲染分页链接。/
原文地址: https://www.cveoy.top/t/topic/pKpF 著作权归作者所有。请勿转载和采集!