Spring Boot新手求助:如何用JpaRepository在JSP中实现表格分页?
当然可以用 JpaRepository<T, I> 配合JSP实现表格分页,我来帮你完善现有代码,轻松搞定这个问题~
第一步:修正Controller中的分页数据传递
你当前的Controller里把分页数据存到了data属性,但JSP里用的是${list},而且旧的PageRequest构造器已经过时了,先调整这部分:
@Controller public class EmployeeController { @Autowired private EmployeeRepository repo; @GetMapping("/") public String showPaginate(Model m, @RequestParam(defaultValue = "0") int page) { // 用PageRequest.of替代过时的构造器,页码从0开始 Page<Emp> empPage = repo.findAll(PageRequest.of(page, 4)); // 将Page对象直接存入Model,方便JSP获取分页相关信息 m.addAttribute("page", empPage); return "index"; } }
第二步:调整JSP中的数据遍历逻辑
Page对象的getContent()方法才会返回当前页的员工列表,所以要修改<c:forEach>的数据源:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 确保页面顶部引入JSTL标签库 --> <table border="2" width="70%" cellpadding="3" class="table"> <thead class="thead-dark"> <tr align="center"> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Designation</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> <!-- 遍历Page对象的content属性获取当前页数据 --> <c:forEach var="emp" items="${page.content}"> <tr align="center"> <td>${emp.id}</td> <td>${emp.name}</td> <td>${emp.designation}</td> <td><a href="editemp/${emp.id}" class="btn btn-outline-info">Edit</a></td> <td><a href="deleteemp/${emp.id}" class="btn btn-outline-danger">Delete</a></td> </tr> </c:forEach> </tbody> </table>
第三步:添加分页导航栏
Page对象提供了大量分页相关的方法(比如getTotalPages()总页数、hasPrevious()是否有上一页等),直接用这些方法构建分页按钮:
<hr> <!-- 分页导航 --> <div class="d-flex justify-content-center mt-3"> <ul class="pagination"> <!-- 上一页按钮 --> <li class="page-item <c:if test="${!page.hasPrevious()}">disabled</c:if>"> <a class="page-link" href="?page=${page.number - 1}">上一页</a> </li> <!-- 页码列表 --> <c:forEach begin="0" end="${page.totalPages - 1}" var="pageNum"> <li class="page-item <c:if test="${pageNum == page.number}">active</c:if>"> <a class="page-link" href="?page=${pageNum}">${pageNum + 1}</a> </li> </c:forEach> <!-- 下一页按钮 --> <li class="page-item <c:if test="${!page.hasNext()}">disabled</c:if>"> <a class="page-link" href="?page=${page.number + 1}">下一页</a> </li> </ul> </div> <!-- 显示分页统计信息 --> <div class="text-center mt-2"> 当前第 ${page.number + 1} 页,共 ${page.totalPages} 页,总计 ${page.totalElements} 条记录 </div>
额外注意事项
如果你的项目还没引入JSTL依赖,需要在pom.xml(Maven)中添加:
<dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
这样就完全基于JpaRepository实现了JSP分页,不需要手动写SQL和复杂的页码逻辑,所有分页相关的计算都由Spring Data JPA帮你完成啦~
内容的提问来源于stack exchange,提问作者java-user
相关产品推荐
相关产品推荐

