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