分页的实现
效果:
具体代码如下:
在bean实体中:(六个要素)
private int pc;// 当前页码page code // private int tp;// 总页数total page private int tr;// 总记录数total record private int ps;// 每页记录数page size private List<T> beanList;// 当前页的记录 private String url;//它就是url后的条件!
/** * 计算总页数 * @return */ public int getTp() { // 通过总记录数和每页记录数来计算总页数 int tp = tr / ps; return tr%ps==0 ? tp : tp+1; }
servlet中findAll方法和四个条件搜索:
1 public String findAll(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 /* 4 * 1. 获取页面传递的pc 5 * 2. 给定ps的值 6 * 3. 使用pc和ps调用service方法,得到PageBean,保存到request域 7 * 4. 转发到list.jsp 8 */ 9 int pc = getPc(request);//得到pc 10 int ps = 10;//给定ps的值,第页10行记录 11 PageBean<Customer> pb = customerService.findAll(pc, ps);//传递pc, ps给Service,得到PageBean 12 13 // 设置url 14 pb.setUrl(getUrl(request)); 15 16 request.setAttribute("pb", pb);//保存到request域中 17 return "f:/list.jsp";//转发到list.jsp 18 }
1 public String query(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 // System.out.println(getUrl(request)); 4 /* 5 * 0. 把条件封装到Customer对象中 6 * 1. 得到pc 7 * 2. 给定ps 8 * 3. 使用pc和ps,以及条件对象,调用service方法得到PageBean 9 * 4. 把PageBean保存到request域中 10 * 5. 转发到list.jsp 11 */ 12 // 获取查询条件 13 Customer criteria = CommonUtils.toBean(request.getParameterMap(), Customer.class); 14 15 /* 16 * 处理GET请求方式编码问题! 17 */ 18 criteria = encoding(criteria); 19 20 int pc = getPc(request);//得到pc 21 int ps = 10;//给定ps的值,第页10行记录 22 PageBean<Customer> pb = customerService.query(criteria, pc, ps); 23 24 // 得到url,保存到pb中 25 pb.setUrl(getUrl(request)); 26 27 request.setAttribute("pb", pb); 28 return "f:/list.jsp"; 29 } 30
其中:要使用到的工具:
获取当前页码:pc
1 /** 2 * 获取pc 3 * @param request 4 * @return 5 */ 6 private int getPc(HttpServletRequest request) { 7 /* 8 * 1. 得到pc 9 * 如果pc参数不存在,说明pc=1 10 * 如果pc参数存在,需要转换成int类型即可 11 */ 12 String value = request.getParameter("pc"); 13 if(value == null || value.trim().isEmpty()) { 14 return 1; 15 } 16 return Integer.parseInt(value); 17 }
处理四个参数的编码等问题:
/** * 处理四样 * @param criteria * @return * @throws UnsupportedEncodingException */ private Customer encoding(Customer criteria) throws UnsupportedEncodingException { String cname = criteria.getCname(); String gender = criteria.getGender(); String cellphone = criteria.getCellphone(); String email = criteria.getEmail(); if(cname != null && !cname.trim().isEmpty()) { cname = new String(cname.getBytes("ISO-8859-1"), "utf-8"); criteria.setCname(cname); } if(gender != null && !gender.trim().isEmpty()) { gender = new String(gender.getBytes("ISO-8859-1"), "utf-8"); criteria.setGender(gender); } if(cellphone != null && !cellphone.trim().isEmpty()) { cellphone = new String(cellphone.getBytes("ISO-8859-1"), "utf-8"); criteria.setCellphone(cellphone); } if(email != null && !email.trim().isEmpty()) { email = new String(email.getBytes("ISO-8859-1"), "utf-8"); criteria.setEmail(email); } return criteria; }
截取url:
1 /** 2 * 截取url 3 * /项目名/Servlet路径?参数字符串 4 * @param request 5 * @return 6 */ 7 private String getUrl(HttpServletRequest request) { 8 String contextPath = request.getContextPath();//获取项目名 9 String servletPath = request.getServletPath();//获取servletPath,即/CustomerServlet 10 String queryString = request.getQueryString();//获取问号之后的参数部份 11 12 // 判断参数部份中是否包含pc这个参数,如果包含,需要截取下去,不要这一部份。 13 if(queryString.contains("&pc=")) { 14 int index = queryString.lastIndexOf("&pc="); 15 queryString = queryString.substring(0, index); 16 } 17 18 return contextPath + servletPath + "?" + queryString; 19 }
service中直接以来dao,怎么来怎么走,
在dao层中:
findAll方法:
1 /** 2 * 查询所有 3 * @return 4 */ 5 public PageBean<Customer> findAll(int pc, int ps) { 6 try { 7 /* 8 * 1. 他都PageBean对象pb 9 * 2. 设置pb的pc和ps 10 * 3. 得到tr,设置给pb 11 * 4. 得到beanList,设置给pb 12 * 5. 返回pb 13 */ 14 PageBean<Customer> pb = new PageBean<Customer>(); 15 pb.setPc(pc); 16 pb.setPs(ps); 17 /* 18 * 得到tr 19 */ 20 String sql = "select count(*) from t_customer"; 21 Number num = (Number)qr.query(sql, new ScalarHandler()); 22 int tr = num.intValue(); 23 pb.setTr(tr); 24 /* 25 * 得到beanList 26 */ 27 sql = "select * from t_customer order by cname limit ?,?"; 28 List<Customer> beanList = qr.query(sql, 29 new BeanListHandler<Customer>(Customer.class), 30 (pc-1)*ps, ps); 31 pb.setBeanList(beanList); 32 return pb; 33 } catch(SQLException e) { 34 throw new RuntimeException(e); 35 } 36 }
2,多条件组合查询的query方法:
1 public PageBean<Customer> query(Customer criteria, int pc, int ps) { 2 try { 3 /* 4 * 1. 创建PageBean对象 5 * 2. 设置已有的属性,pc和ps 6 * 3. 得到tr 7 * 4. 得到beanList 8 */ 9 /* 10 * 创建pb,设置已有属性 11 */ 12 PageBean<Customer> pb = new PageBean<Customer>(); 13 pb.setPc(pc); 14 pb.setPs(ps); 15 16 /* 17 * 得到tr 18 */ 19 20 /* 21 * 1. 给出一个sql语句前半部 22 */ 23 StringBuilder cntSql = new StringBuilder("select count(*) from t_customer"); 24 StringBuilder whereSql = new StringBuilder(" where 1=1"); 25 /* 26 * 2. 判断条件,完成向sql中追加where子句 27 */ 28 /* 29 * 3. 创建一个ArrayList,用来装载参数值 30 */ 31 List<Object> params = new ArrayList<Object>(); 32 String cname = criteria.getCname(); 33 if(cname != null && !cname.trim().isEmpty()) { 34 whereSql.append(" and cname like ?"); 35 params.add("%" + cname + "%"); 36 } 37 38 String gender = criteria.getGender(); 39 if(gender != null && !gender.trim().isEmpty()) { 40 whereSql.append(" and gender=?"); 41 params.add(gender); 42 } 43 44 String cellphone = criteria.getCellphone(); 45 if(cellphone != null && !cellphone.trim().isEmpty()) { 46 whereSql.append(" and cellphone like ?"); 47 params.add("%" + cellphone + "%"); 48 } 49 50 String email = criteria.getEmail(); 51 if(email != null && !email.trim().isEmpty()) { 52 whereSql.append(" and email like ?"); 53 params.add("%" + email + "%"); 54 } 55 56 /* 57 * select count(*) .. + where子句 58 * 执行之 59 */ 60 Number num = (Number)qr.query(cntSql.append(whereSql).toString(), 61 new ScalarHandler(), params.toArray()); 62 int tr = num.intValue(); 63 pb.setTr(tr); 64 65 /* 66 * 得到beanList 67 */ 68 StringBuilder sql = new StringBuilder("select * from t_customer"); 69 // 我们查询beanList这一步,还需要给出limit子句 70 StringBuilder limitSql = new StringBuilder(" limit ?,?"); 71 // params中需要给出limit后两个问号对应的值 72 params.add((pc-1)*ps); 73 params.add(ps); 74 // 执行之 75 List<Customer> beanList = qr.query(sql.append(whereSql).append(limitSql).toString(), 76 new BeanListHandler<Customer>(Customer.class), 77 params.toArray()); 78 pb.setBeanList(beanList); 79 80 return pb; 81 82 } catch(SQLException e) { 83 throw new RuntimeException(e); 84 } 85 }
在jsp页面中的使用:
list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>客户列表</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h3 align="center">客户列表</h3> <table border="1" width="70%" align="center"> <tr> <th>客户姓名</th> <th>性别</th> <th>生日</th> <th>手机</th> <th>邮箱</th> <th>描述</th> <th>操作</th> </tr> <%-- 要遍历提PageBean的beanList这个集合 --%> <c:forEach items="${pb.beanList}" var="cstm"> <tr> <td>${cstm.cname }</td> <td>${cstm.gender }</td> <td>${cstm.birthday }</td> <td>${cstm.cellphone }</td> <td>${cstm.email }</td> <td>${cstm.description }</td> <td> <a href="<c:url value='/CustomerServlet?method=preEdit&cid=${cstm.cid }'/>">编辑</a> <a href="<c:url value='/msg.jsp'/>">删除</a> </td> </tr> </c:forEach> </table> <br/> <%-- 给出分页相差的链接 --%> <center> 第${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> <c:otherwise> <%-- 当总页数>10时,通过公式计算出begin和end --%> <c:set var="begin" value="${pb.pc-5 }" /> <c:set var="end" value="${pb.pc+4 }" /> <%-- 头溢出 --%> <c:if test="${begin < 1 }"> <c:set var="begin" value="1" /> <c:set var="end" value="10" /> </c:if> <%-- 尾溢出 --%> <c:if test="${end > pb.tp }"> <c:set var="begin" value="${pb.tp - 9 }" /> <c:set var="end" value="${pb.tp }" /> </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> </center> </body> </html>