实体类 public class Pages { //当前页数 private int currentPageNo; //每页记录数 private int pageSize; //总记录数 private int totalCount; //总页数 private int totalPageCount; public int getCurrentPageNo() { return currentPageNo; } public void setCurrentPageNo(int currentPageNo) { this.currentPageNo = currentPageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } //总记录数 public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; this.totalPageCount=this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1; } //总页数 public int getTotalPageCount() { return totalPageCount; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } }
sql代码
public List<Category> getPage(int from, int pageSize) { List<Category> list = new ArrayList<>(); try { String sql = "SELECT c1.*,c2.`name` AS parentName FROM `easybuy_product_category` c1 left join `easybuy_product_category` c2 on (c1.parentId = c2.Id) order by c1.`type` limit ?,?"; Object[] params = {from,pageSize}; rs = executeQuery(sql,params); while (rs.next()){ Category category = tableToEntity(rs); category.setParentName(rs.getString("parentName")); list.add(category); } }catch (Exception e){ e.printStackTrace(); }finally { closeConnection(); } return list; }
servlet
if("getPage".equals(action)){ Pages pages = new Pages(); String pageIndex = request.getParameter("pageIndex"); if(pageIndex==null){ pages.setCurrentPageNo(1); }else { pages.setCurrentPageNo(Integer.parseInt(pageIndex)); } //设置每页显示数 pages.setPageSize(8); //设置总记录数 pages.setTotalCount(categoryService.findCount()); //获取分页数据 //当前页-1乘以每页显示数 int from = ((pages.getCurrentPageNo()-1)*pages.getPageSize()); List<Category> list = categoryService.findPage(from, pages.getPageSize()); Map<String,Object> maps = new HashMap<>(); maps.put("pages",pages); maps.put("list",list); out.println(JSONArray.toJSONString(maps)); }
jsp页面
//分页function getCategoryList(pageIndex) { $.getJSON(rootpath+"/category?action=getPage","pageIndex="+pageIndex,function (data) { var pages = data.pages; str="共有"+pages.totalPageCount+"个分类,当前页:【"+pages.currentPageNo+"/"+pages.totalPageCount+"】"; str+="<span style='float: right'>"; if(pages.currentPageNo!=1){ str+="<button οnclick='getCategoryList(1)'>首页</button>"; str+="<button οnclick='getCategoryList("+(pages.currentPageNo-1)+")'>上一页</button>"; } if(pages.currentPageNo!=pages.totalPageCount){ str+="<button οnclick='getCategoryList("+(pages.currentPageNo+1)+")'>下一页</button>"; str+="<button οnclick='getCategoryList("+(pages.totalPageCount)+")'>末页</button>"; } $(".c_pages").html(str); }) }