结合Bootstrap的分页插件实现分页,其中策略是每次显示5个按钮,然后根据当前页的不同来进行不同的显示:
1. 当前页<3,如果当前页大于5页就显示前五页,不然就显示1~totalPage。
2. 当前页<=3 && <=totalPage-3,显示当前页往前两,往后两页,即 currentPage-2, currentPage-1, currentPage, currentPage+1, currentPage+2
3. 当前页>=totalPage-2时,如果页数够的话就显示最后5页,否则的话就从第一页开始显示1~totalPage页。
效果大概是这样的:
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <div class="paging">
<nav aria-label="Page navigation">
<ul class="pagination"> <!-- 当前页不为第一页时显示前一页 -->
<c:if test="${page.pageNumber!=1 && page.totalPage>1 }">
<li>
<a href="<c:url value="${paginationLocation }?pageNumber=${page.pageNumber-1 }${paginationParams ? '&'+paginationParams : '' }"/>" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if> <%-- 根据不同的情况显示分页 --%>
<c:choose> <%-- 当总页数大于1时才显示分页按钮 --%>
<c:when test="${page.totalPage<=1 }">
</c:when> <%-- 当前页<=3 && <=total-3,普通显示 --%>
<c:when test="${page.pageNumber>=3 && page.totalPage-page.pageNumber>=3 }">
<c:forEach begin="${page.pageNumber-2 }" end="${page.pageNumber+2 }" var="index">
<li <c:if test="${page.pageNumber==index }">class="active"</c:if>>
<a href="<c:url value="${paginationLocation }?pageNumber=${index }${paginationParams ? '&'+paginationParams : '' }"/>">${index }</a>
</li>
</c:forEach>
</c:when> <%-- 当<3时显示 --%>
<c:when test="${page.pageNumber<3 }">
<c:forEach begin="1" end="${page.totalPage<5 ? page.totalPage : 5 }" var="index">
<li <c:if test="${page.pageNumber==index }">class="active"</c:if>>
<a href="<c:url value="${paginationLocation }?pageNumber=${index }${paginationParams ? '&'+paginationParams : '' }"/>">${index }</a>
</li>
</c:forEach>
</c:when> <%-- 当>=totalPage-2,显示最后5页 --%>
<c:when test="${page.totalPage-page.pageNumber<3}">
<c:forEach begin="${(page.totalPage-5<1) ? 1 : (page.totalPage-5) }" end="${page.totalPage }" var="index">
<li <c:if test="${page.pageNumber==index }">class="active"</c:if>>
<a href="<c:url value="${paginationLocation }?pageNumber=${index }${paginationParams ? '&'+paginationParams : '' }"/>">${index }</a>
</li>
</c:forEach>
</c:when> </c:choose> <!-- 当不为最后一页时显示下一页按钮 -->
<c:if test="${page.pageNumber!=page.totalPage && page.totalPage>1}">
<li>
<a href="<c:url value="${paginationLocation }?pageNumber=${page.pageNumber+1 }${paginationParams ? '&'+paginationParams : '' }"/>" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if> </ul>
</nav>
</div>
因为include过来的可以共享当前页中的变量,所以只需要在当前页中声明变量在被引入的分页片段中也可以访问得到,相当于是传参数了,引入分页:
<!-- 引入分页 -->
<c:set var="paginationLocation" value="/companyHr/myCompanyEntry" />
<%@include file="/WEB-INF/jsp/commons/pagination/pagination.jspf" %>
.paging是为了让其居中:
/*分页一直是固定大小并且居中的*/
.paging{
width:400px;
margin:0px auto;
}
其它相关依赖自行引入。
.