先阐述一下具体的思路:
- 第一步:编写一个分页的类里面包含了(第一页,最后一页,下一页,上一页,当前页,页码等等)对象和方法。
- 第二步:进行分页的业务处理。
> ------**分页类**------------package newRelease.dao;import java.util.ArrayList;
/*** * @author wfy* 分页算法 根据总记录数,和每页显示记录数实现分页功能* @param <T>*/
public class PageBean<T>{private ArrayList<T> pageList; //ArrayList泛型private int pageSize; //每页多少条记录private int rowCount; //总共有多少条记录private int totalPage; //总共有多少页private int currentPage; //当前页码private boolean firstPage; //第一页,bool类型private boolean lastPage; //最后一页,bool类型private int previousPageCount; //前一页private int nextPageCount; //后一页private int beginPage; //开始页private int endPage; //尾页public PageBean(){pageSize = 4; //设置一页只有4条记录}public void setPageList(ArrayList<T> pageList) {this.pageList = pageList; //设置PageList对象}public ArrayList<T> getPageList(){return pageList;}public int getRowCount(){return rowCount;}public void setRowCount(int rowCount){this.rowCount = rowCount;totalPage = rowCount % pageSize != 0 ? rowCount / pageSize + 1 : rowCount / pageSize; //使用了if : 条件运算符}public int getCurrentPage(){return currentPage;}public void setCurrentPage(int currentPage){this.currentPage = currentPage;//判断如果超过了totalPageif(currentPage > totalPage){this.currentPage = totalPage;}if(currentPage < 1){this.currentPage = 1;}previousPageCount = currentPage - 1;nextPageCount = currentPage + 1;//如果当前页是第一页,则为首页if(this.currentPage == 1){firstPage = true;} else{firstPage = false;}if(this.currentPage == totalPage){lastPage = true;} else{lastPage = false;}//对需要显示的页码进行判断从beginPage开始,endPage结束beginPage = this.currentPage <= 5 ? 1 : this.currentPage;endPage = beginPage >=totalPage - 5 ? totalPage:beginPage +5;if(endPage - 5 > 0 && endPage - 5 < beginPage){beginPage = endPage - 5;}}public int getPreviousPageCount(){return previousPageCount;}public int getNextPageCount(){return nextPageCount;}public int getPageSize(){return pageSize;}public void setPageSize(int pageSize){this.pageSize = pageSize;}public int getTotalPage(){return totalPage;}public boolean isFirstPage(){return firstPage;}public boolean isLastPage(){return lastPage;}public int getBeginPage(){return beginPage;}public int getEndPage(){return endPage;}
}
业务处理代码
//获取页码String curPage = request.getParameter("curPage");//创建一个pageBean对象PageBean pageBean = new PageBean();//通过getNum()方法得到总记录条数rowCount = bookDAO.getNum();//把相关参数存放到pageBean对象中pageBean.setRowCount(rowCount); pageBean.setCurrentPage(curPage);//把页码传递到getBook()方法中,得到相应的分页数据信息bookList = bookDAO.getBook(pageBean.getCurrentPage());//把booklist中的数据存放到pageBean中pageBean.setPageList(booksList);//用于参数传递request.setAttribute("pagebean", pageBean);