1、分页工具
package com.life.utils; public class DividePage { /** * 总共有几页 */ private int pageSize; /** * 总共有多少条记录 */ private int recordCount; /** * 当前第几页 */ private int currentPage; /** * 页面链接 */ private String pageUrl; public DividePage(int pageSize, int recordCount, int currentPage,String pageUrl) { super(); this.pageSize = pageSize; this.recordCount = recordCount; this.pageUrl=pageUrl; setCurrentPage(currentPage); } public DividePage(int pageSize, int recordCount,String pageUrl) { this(pageSize, recordCount, 1,pageUrl); } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * @return 总页数 */ public int getpageCount() { int size = recordCount / pageSize; int mod = recordCount % pageSize; if (mod != 0) { size++; } return recordCount == 0 ? 1 : size; } public int getFromIndex() { return (currentPage - 1) * pageSize; } public int getToIndex() { return pageSize; } public String get(){ return "123"; } public int getCurrentPage() { return currentPage; } /** * @param currentPage */ public void setCurrentPage(int currentPage) { int ValidPage = currentPage <= 0 ? 1 : currentPage; ValidPage = ValidPage > getCurrentPage() ? getpageCount() : ValidPage; this.currentPage = currentPage; } public String getPagination() { String url = pageUrl.contains("?") ? pageUrl : pageUrl + "?"; if (!url.endsWith("?") && !url.endsWith("&")) { url += "&"; } StringBuffer buffer = new StringBuffer(); buffer.append("第" + currentPage + "/" + getpageCount() + " 页 共" + recordCount + "记录 "); buffer.append(currentPage == 1 ? "第一页" : "<a href='" + url + "page=1'>第一页</a> "); buffer.append(currentPage == 1 ? " 上一页" : "<a href='" + url + "page=" + (currentPage - 1) + "'> 上一页</a> "); buffer.append(currentPage == getpageCount() ? " 下一页" : "<a href='" + url + "page=" + (currentPage + 1) + "'> 下一页</a> "); buffer.append(currentPage == getpageCount() ? " 最后一页" : "<a href='" + url + "page=" + getpageCount() + "'> 最后一页</a> "); return buffer.toString(); } public int getpageSize() { return pageSize; } public void setpageSize(int pageSize) { this.pageSize = pageSize; } public int getRecordCount() { return recordCount; } public void setRecordCount(int recordCount) { this.recordCount = recordCount; } }
2、使用
recordCount:记录总数,select count(*) from Coupon从数据库获得
page:第几页
dividePage :分页的语句,应为action类的全局变量
pageUrl 一般是action名称+?+其他除page值的参数
int recordCount; recordCount = couponService.getTotalCount( "select count(*) from Coupon", null); coupons = couponService.list(page); int currentPage = page; String pageUrl = "showCoupons_manage"; DividePage dividePage = new DividePage(Constants.PageSize, recordCount,currentPage, pageUrl); pageString = dividePage.getPagination();
3、jsp页面
<s:property value="pageString" escape="false" />
Done