日期:2014-05-16  浏览次数:20447 次

第十五天3月10日之JDBC案例、分页技术、大数据(文本、图片)存储、批处理和存储过程的调用


一、大结果集的分页
MySQL:
limit M,N;
M:每页开始记录的索引。第一页的第一条记录的索引为0
N:每次取多少条

每页显示10条记录
第一页:M=0 N=10
第二页:M=10 N=10
第三页:M=20 N=10

第X页: M=(X-1)*N N=10

----------------------------------
总共需要多少页?
总页数=总记录条数%10==0?总记录条数/10:(总记录条数/10+1)


二、分页代码:
1、DAO:
 /**
  * 查询分页记录
  * @param startIndex 开始的索引
  * @param pageSize 每次取到的条数
  * @return
  */
 List<Customer> findPageRecords(int startIndex,int pageSize);
 /**
  * 查询总记录的条数
  * @return
  */
 int findTotalRecords();
2、Page对象设计:
 public class Page {
   private int pageSize = 10;//每页显示多少条记录
   private int currentPageNum;//当前查看的页码
   private int totalPage;//总页数
   private List records;//分页数据
   private int startIndex;//每页开始记录的索引号
   private int totalRecords;//总记录条数
   
   public Page(int currentPageNum,int totalRecords){
    this.currentPageNum = currentPageNum;
    this.totalRecords = totalRecords;
    //计算总页数
    totalPage = totalRecords%pageSize==0?totalRecords/pageSize:(totalRecords/pageSize+1);
    //计算每页开始记录的索引号
    startIndex = (currentPageNum-1)*pageSize;
   }
  
 }
2、SERVICE:

 /**
  * 查询封装了分页信息的Page对象
  * @param pageNum 用户要看的页码。如果为null或者“”,默认值为1
  * @return
  */
 Page findPage(String pageNum);
 
 参考实现:
  public Page findPage(String pageNum) {
   int num = 1;//用户要看的页码
   if(pageNum!=null&&!pageNum.equals("")){
    num = Integer.parseInt(pageNum);
   }
   int totalRecords = dao.findTotalRecords();
   Page page = new Page(num,totalRecords);
   List<Customer> cs = dao.findPageRecords(page.getStartIndex(), page.getPageSize());
   page.setRecords(cs);
   return page;
  }
3、Servlet
 String pageNum = request.getParameter("pageNum");
 Page page = s.findPage(pageNum);
 request.setAttribute("page", page);
 request.getRequestDispatcher("/listCustomer.jsp").forward(request, response);


4.显示数据的jsp:

<c:forEach items="${page.records}" var="c" varStatus="vs">
 <tr class="${vs.index%2==0?'odd':'even' }">
 <td nowrap="nowrap">
 <input type="checkbox" name="ids" value="${c.id}">
 </td>
 <td nowrap="nowrap">${c.name}</td>
 <td nowrap="nowrap">${c.gender=='male'?'男':'女' }</td>
 <td nowrap="nowrap">${c.birthday}</td>
 <td nowrap="nowrap">${c.cellphone}</td>
 <td nowrap="nowrap">${c.email}</td>
 <td nowrap="nowrap">${c.hobby}</td>
 <td nowrap="nowrap">${c.type}</td>
 <td nowrap="nowrap">${fn:substring(c.description,0,3)}...</td>
 <td nowrap="nowrap">[<a
  href="${pageContext.request.contextPath}/servlet/CenterController?op=editUI&id=${c.id}">修改</a>]
  [<a href="javascript:delOne('${c.id}')">删除</a>]</td>