核心思路: 前端根据该模板先划分出对应字段,然后使用Thymeleaf的th-each方法批量获取单页内容,以及分页页号之类的东西。
后端做的事比较多,使用JPA分页查询后可以获得单页的内容以及所有数量,接着设置到Model中返回视图。
数据库格式:
CNO, CNAME, SEX, AGE, ADDRESS
前端
对于分页组件,需要包含以下四种情况:
- 总页数只有一页,当前在第一页,前后切换均disable
- 总页数大于一页,当前在第一页,前切换disable,后切换生效
- 总页数大于一页,当前在第一页之后且不在最后一页,前后切换均生效
- 总页数大于一页,当前页在最后一页,前切换生效,后切换disable
对应的 Thymeleaf 代码为:
<ul class="pagination" th:if="${currentPage == 1 && currentPage == totalPage}">
<li class="disabled"><span>«</span></li>
<li class="active"><span>1</span></li>
<li class="disabled"><span>»</span></li>
</ul>
<ul class="pagination" th:if="${currentPage == 1 && currentPage != totalPage}">
<li class="disabled"><span>«</span></li>
<li th:each="num : ${pageList}" th:class="${num==currentPage?'active':''}">
<span th:text="${num}" th:if="${num == currentPage}"></span>
<a th:href="'#' + ${num}" th:if="${num != currentPage}" th:text="${num}"></a>
</li>
<li><a href="#!">»</a></li>
</ul>
<ul class="pagination" th:if="${currentPage != 1 && currentPage != totalPage}">
<li><a th:href="'/student/index?current=' + ${currentPage - 1}">«</a></li>
<li th:each="num : ${pageList}" th:class="${num==currentPage?'active':''}">
<span th:text="${num}" th:if="${num == currentPage}"></span>
<a th:href="'#' + ${num}" th:if="${num != currentPage}" th:text="${num}"></a>
</li>
<li><a th:href="'/student/index?current=' + ${currentPage + 1}">»</a></li>
</ul>
<ul class="pagination" th:if="${currentPage!= 1 && currentPage == totalPage}">
<li ><a th:href="'/student/index?current=' + ${currentPage - 1}">«</a></li>
<li th:each="num : ${pageList}" th:class="${num==currentPage?'active':''}">
<span th:text="${num}" th:if="${num == currentPage}"></span>
<a th:href="'#' + ${num}" th:if="${num != currentPage}" th:text="${num}"></a>
</li>
<li class="disabled"><span>»</span></li>
</ul>
至于数据显示就修改一下table表结构以及使用 th-each遍历获取数据就行。
后端
使用 JPA分页查询 的 PageRequest 来获取分页数据,并使用 CustomerRespository.findAll 来获取当前分页的所有数据,返回 Page<Custormer>
对象,再调用 page.getPageContent
来获取 List<Customer>
结果,顺便拿到所有数据个数,以及最大分页数。
添加Model中传入视图解析器即可。