在开发过程中,前端分页是一个常见的需求,它可以帮助用户更高效、直观地浏览大量数据。Thymeleaf 作为一种流行的模板引擎,可以轻松实现前端分页。下面,我将详细介绍如何使用 Thymeleaf 来实现这一功能。
1. 准备工作
首先,确保你的项目中已经引入了 Thymeleaf 依赖。以下是一个 Maven 依赖示例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 创建分页模型
在 Thymeleaf 中,我们需要创建一个分页模型来存储分页信息。以下是一个简单的分页模型示例:
public class Pagination {
private int currentPage;
private int pageSize;
private int totalRecords;
private List<T> records;
// 省略构造方法、getter 和 setter
}
其中,currentPage 表示当前页码,pageSize 表示每页显示的记录数,totalRecords 表示总记录数,records 表示当前页的记录列表。
3. 创建分页控制器
在 Spring MVC 中,我们需要创建一个分页控制器来处理分页请求。以下是一个简单的分页控制器示例:
@Controller
public class PaginationController {
@Autowired
private YourService yourService;
@GetMapping("/your-data")
public String showYourData(Model model, @RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
Pagination pagination = yourService.findYourData(page, size);
model.addAttribute("pagination", pagination);
return "your-data";
}
}
其中,YourService 是用于查询数据的业务层接口,findYourData 方法负责查询分页数据。
4. 创建 Thymeleaf 模板
在 Thymeleaf 模板中,我们可以使用 Thymeleaf 的分页标签来实现前端分页。以下是一个简单的 Thymeleaf 模板示例:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>分页示例</title>
</head>
<body>
<div>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
</tr>
</thead>
<tbody>
<tr th:each="record : ${pagination.records}">
<td th:text="${record.id}"></td>
<td th:text="${record.name}"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${pagination.totalPages > 1}">
<ul>
<li th:if="${pagination.currentPage > 1}">
<a th:href="@{/your-data(page=${pagination.currentPage - 1}, size=${pagination.pageSize})}">上一页</a>
</li>
<li th:each="page : ${#numbers.sequence(1, pagination.totalPages)}">
<a th:if="${page == pagination.currentPage}" th:text="${page}" th:style="color: red;"></a>
<a th:if="${page != pagination.currentPage}" th:href="@{/your-data(page=${page}, size=${pagination.pageSize})}">[[${page}]]</a>
</li>
<li th:if="${pagination.currentPage < pagination.totalPages}">
<a th:href="@{/your-data(page=${pagination.currentPage + 1}, size=${pagination.pageSize})}">下一页</a>
</li>
</ul>
</div>
</body>
</html>
在这个示例中,我们使用了 th:each 标签来遍历分页数据,并使用 th:if 和 th:else 标签来显示分页导航。
5. 总结
通过以上步骤,我们可以使用 Thymeleaf 实现前端分页。这种方式简单易用,可以帮助用户更高效、直观地浏览大量数据。在实际开发中,你可以根据自己的需求进行扩展和优化。
