引入jar包
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency> <!--解决pagehelper分页警告 --> <!-- <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.4.2-fix</version> </dependency> -->
前台分页
<div class="col-md-12 text-center"> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="/details?${detail.id}?pn=1" aria-label="First"> <span aria-hidden="true">首页</span> </a> </li> <c:if test="${pageInfo.hasPreviousPage}"> <li > <a href="/details?${detail.id}?pn=${pageInfo.pageNum-1}" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> </c:if> <c:if test="${!pageInfo.hasPreviousPage}"> <li > <a href="#" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> </c:if> <!--循环遍历连续显示的页面,若是当前页就高亮显示,并且没有链接--> <c:forEach items="${pageInfo.navigatepageNums}" var="page_num"> <c:if test="${page_num == pageInfo.pageNum}"> <li class="active"><a href="#">${page_num}</a></li> </c:if> <c:if test="${page_num != pageInfo.pageNum}"> <li><a href="/details?${detail.id}?pn=${page_num}">${page_num}</a></li> </c:if> </c:forEach> <c:if test="${pageInfo.hasNextPage}"> <li> <a href="/details?${detail.id}?pn=${pageInfo.pageNum+1}" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> </c:if> <c:if test="${!pageInfo.hasNextPage}"> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> </c:if> <li> <a href="/details?${detail.id}?pn=${pageInfo.pages}" aria-label="Last"> <span aria-hidden="true">尾页</span> </a> </li> </ul> </nav> <!-- <div style="text-align: center;"> <ul id="pagination" class="pagination"></ul> </div> --> </div>
Controller
@RequestMapping("/details") public String webdetail(Model model,@RequestParam(required = false,defaultValue = "1",value = "pn")Integer pn)throws Exception { PageInfo pageInfo = detailService.commentList(pn); model.addAttribute("pageInfo", pageInfo); return "details"; }
Service
@Override public PageInfo commentList(Integer pn) throws Exception { //引入分页查询,使用PageHelper分页功能 //在查询之前传入当前页,然后多少记录 PageHelper.startPage(pn,5); //startPage后紧跟的这个查询就是分页查询 CommentExample example = new CommentExample(); List<Comment> emps = commentMapper.selectByExample(example); //使用PageInfo包装查询结果,只需要将pageInfo交给页面就可以 PageInfo pageInfo = new PageInfo<>(emps,5); //pageINfo封装了分页的详细信息,也可以指定连续显示的页数 return pageInfo; }