分页
package cn.itcast.tool.paging; import java.util.List; public class PageBean <T>{ private int pc;//Page Code当前页数 private int ps;//Page size每页记录数 private int tp;//total page总页数 private int tr;//total recode总记录数 private String url; private List<T> beanList;//当前页的记录 public int getPc() { return pc; } public void setPc(int pc) { this.pc = pc; } public int getPs() { return ps; } public void setPs(int ps) { this.ps = ps; } public int getTp() { tp=(tr%ps==0)?tr/ps:tr/ps+1; return tp; } public void setTp(int tp) { this.tp = tp; } public int getTr() { return tr; } public void setTr(int tr) { this.tr = tr; } public List<T> getBeanList() { return beanList; } public void setBeanList(List<T> beanList) { this.beanList = beanList; } public PageBean() { super(); } public PageBean(int pc, int ps, int tp, int tr,String url, List<T> beanList) { super(); this.pc = pc; this.ps = ps; this.tp = tp; this.tr = tr; this.url=url; this.beanList = beanList; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package cn.itcast.tool.paging; import javax.servlet.http.HttpServletRequest; public class PageUtils { /** * 通过request得到不包括页码的路径 * @param request * @return */ public static String getUrl(HttpServletRequest request){ String contextPath=request.getContextPath();//获取项目名 String servletPath=request.getServletPath();//获取servletPath,即/CustomerServlet String queryString=request.getQueryString();//获取问号之后的参数部分 if(queryString!=null){ if(queryString.contains("&pc=")){//判断参数部分中是否包含pc这个参数,如果包含就截取 int index=queryString.lastIndexOf("&pc="); queryString=queryString.substring(0,index); } } return contextPath+servletPath+"?"+queryString; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 第${pb.pc }页/共${pb.tp }页 <a href="${pb.url }&pc=1">首页</a> <c:if test="${pb.pc>1 }"> <a href="${pb.url }&pc=${pb.pc-1 }">上一页</a> </c:if> <!-- 计算begin和end者两个东西 --> <c:choose> <%-- 如果总页数不足10页,那么把所有的页数都显示出来 --%> <c:when test="${pb.tp<=10 }"> <c:set var="begin" value="1"/> <c:set var="end" value="${pb.tp}"/> </c:when> <%-- 当总页数>10时,通过公式计算begin和end --%> <c:otherwise> <c:set var="begin" value="${pb.pc-5 }"/> <c:set var="end" value="${pb.pc+4 }"/> <%-- 尾溢出 --%> <c:if test="${end>pb.tp }"> <c:set var="begin" value="${pb.tp-9 }"/> <c:set var="end" value="${pb.tp }"/> </c:if> <br/> <%-- 注意尾溢出要在头溢出之前 --%> <%-- 头溢出 --%> <c:if test="${begin<1 }"> <c:set var="begin" value="1" /> <c:set var="end" value="10" /> </c:if> </c:otherwise> </c:choose> <%-- 循环遍历页码列表 --%> <c:forEach var="i" begin="${begin }" end="${end }"> <c:choose> <c:when test="${i eq pb.pc }"> [${i }] </c:when> <c:otherwise> <a href="${pb.url }&pc=${i}">[${i }]</a> </c:otherwise> </c:choose> </c:forEach> <c:if test="${pb.pc<pb.tp }"> <a href="${pb.url }&pc=${pb.pc+1 }">下一页</a> </c:if> <a href="${pb.url }&pc=${pb.tp }">尾页</a>