Java中数据分页显示之PageBean

 1、编写PageBean工具类:

 package com.accp.page.util;
import java.util.ArrayList;
import java.util.List;

public class PageBean<T> {
private int pageIndex = 1;    // 需要显示的页码
private int totalPages = 1;   // 总页数
private int pageSize = 10;    // 每页记录数
private int totalRecords = 0; // 总记录数
private boolean isHavePrePage = false;  // 是否有上一页
private boolean isHaveNextPage = false; // 是否有下一页

private List<T> pageDatas = new ArrayList<T>();

public int getPageIndex() {
return pageIndex;
}

public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}

public int getPageSize() {
return pageSize;
}

public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}

public int getTotalRecords() {
return totalRecords;
}

public void setTotalRecords(int totalRecords) {
if(totalRecords < 0){
throw new RuntimeException("总记录数不能小于0!");
}
//设置总记录数
this.totalRecords = totalRecords;
//计算总页数
this.totalPages = this.totalRecords/this.pageSize;
if(this.totalRecords%this.pageSize!=0){
this.totalPages++;
}
//计算是否有上一页
if(this.pageIndex>1){
this.isHavePrePage = true;
}else{
this.isHavePrePage = false;
}
//计算是否有下一页
if(this.pageIndex<this.totalPages){
this.isHaveNextPage = true;
}else{
this.isHaveNextPage = false;
}
}

public List<T> getPageDatas() {
return pageDatas;
}

public void setPageDatas(List<T> pageDatas) {
this.pageDatas = pageDatas;
}

public int getTotalPages() {
return totalPages;
}

public boolean getIsHavePrePage() {
return isHavePrePage;
}

public boolean getIsHaveNextPage() {
return isHaveNextPage;
}

}

2、调用方法时的实现(实例):

 public void getPagePetType(PageBean<PetType> pageBean){
    
String sql = "(select t.*,rownum as r from pet_type t where rownum <= "
    
 
                      +pageBean.getPageIndex()*pageBean.getPageSize()+")";
    
sql = "select *  from " + sql + " where r > "
    
 
                     +(pageBean.getPageIndex()-1)*pageBean.getPageSize();
    

    
//计算总记录数
    
String csql = "select count(*) from pet_type";
    
int tcount = ((BigDecimal)super.getObject(csql)).intValue();
    
pageBean.setTotalRecords(tcount);
    

    
List<PetType> petTypes = super.query(sql, new ResultSetter(){
              public List<PetType> setResultSetData(ResultSet rs) throws SQLException {
                    List<PetType> pts = new ArrayList<PetType>();
                     while(rs.next()){
                           PetType pt = new PetType();
                           pt.setId(rs.getInt(1));
                           pt.setName(rs.getString(2));
                           pt.setStatus(rs.getInt(3));
                          pts.add(pt);
                   }
                return pts;
              }
    
});
    
pageBean.setPageDatas(petTypes);
    }

3、访问数据库基类:

public class BaseDaoImpl<T> {
private Connection conn = null;
private PreparedStatement pst = null;
private ResultSet rs = null;

/**
* 更新(增加到、删除、修改)数据的方法

* @param sql
* @param paras
* @return
*/
public int updateData(String sql, Object[] paras) {
this.createPreparedStatement(sql, paras);
int result = 0;
try {
result = this.pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionUtils.close(rs, pst, conn);
}
return result;
}

public int updateData(String sql) {
return this.updateData(sql, null);
}

public List<T> query(String sql, ResultSetter rssetter) {
return this.query(sql,null,rssetter);
}

public List<T> query(String sql, Object[] paras, ResultSetter rssetter) {
this.createPreparedStatement(sql, paras);
try {
ResultSet rs = this.pst.executeQuery();
// 将ResultSet中的数据封装到集合中[]
return rssetter.setResultSetData(rs);
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionUtils.close(rs, pst, conn);
}

return null;
}

public Object getObject(String sql){
return this.getObject(sql, null);
}

public Object getObject(String sql, Object[] paras){
Object robj = null;
this.createPreparedStatement(sql, paras);
try {
ResultSet rs = this.pst.executeQuery();
// 将ResultSet中的数据封装到集合中[]
   if(rs.next()){
   
robj = rs.getObject(1);
   }
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionUtils.close(rs, pst, conn);
}
return robj;
}

/**
* 创建数据操作对象

* @param sql
* @param paras
*/
private void createPreparedStatement(String sql, Object[] paras) {
this.conn = ConnectionUtils.getConnection();
try {
this.pst = this.conn.prepareStatement(sql);
// 绑定动态参数
if (paras != null && paras.length > 0) {
for (int i = 0; i < paras.length; i++) {
this.pst.setObject(i + 1, paras[i]);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

4、jsp页面使用:

提示:可以用JSTL、OGNL、Struts标签,获取pageBean操作相应的分页逻辑控制。



/* * @(#)PageControl.java 1.00 2004-9-22 * * Copyright 2004 2004 . All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.hexiang.utils; /** * PageControl, 分页控制, 可以判断总页数和是否有上下页. * * 2008-07-22 加入输出上下分页HTML代码功能 * * @author HX * @version 1.1 2008-9-22 */ public class PageBean { /** 每页显示记录数 */ private int pageCount; /** 是否有上一页 */ private boolean hasPrevPage; /** 记录总数 */ private int recordCount; /** 是否有下一页 */ private boolean hasNextPage; /**总页面数 */ private int totalPage; /** 当前页码数 */ private int currentPage; /** * 分页前的页面地址 */ private String pageUrl; /** * 输出分页 HTML 页面跳转代码, 分链接和静态文字两种. * 2008-07-22 * @return HTML 代码 */ public String getPageJumpLinkHtml() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf('?') == -1) { pageUrl = pageUrl + '?'; } StringBuffer buff = new StringBuffer("<span id='pageText'>"); // 上一页翻页标记 if(currentPage > 1) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage - 1) + "' title='转到第 " + (currentPage - 1) + " 页'>上一页</a> ] "); } else { buff.append("[ 上一页 ] "); } // 下一页翻页标记 if(currentPage < getTotalPage()) { buff.append("[ <a href='" + pageUrl + "&page=" + (currentPage + 1)+ "' title='转到第 " + (currentPage + 1) + " 页'>下一页</a> ] "); } else { buff.append("[ 下一页 ] "); } buff.append("</span>"); return buff.toString(); } /** * 输出页码信息: 第${currentPage}页/共${totalPage}页 * @return */ public String getPageCountHtml() { return "第" + currentPage + "页/共" + getTotalPage() + "页"; } /** * 输出 JavaScript 跳转函数代码 * @return */ public String getJavaScriptJumpCode() { if(StringUtil.isEmpty(pageUrl)) { return ""; } // 检查是否有参数符号, 没有就加上一个? if(pageUrl.indexOf("?") == -1) { pageUrl = pageUrl + '?'; } return "<script>" + "// 页面跳转函数\n" + "// 参数: 包含页码的表单元素,例如输入框,下拉框等\n" + "function jumpPage(input) {\n" + " // 页码相同就不做跳转\n" + " if(input.value == " + currentPage + ") {" + " return;\n" + " }" + " var newUrl = '" + pageUrl + "&page=' + input.value;\n" + " document.location = newUrl;\n" + " }\n" + " </script>"; } /** * 输出页面跳转的选择框和输入框. 示例输出: * <pre> 转到 <!-- 输出 HTML SELECT 元素, 并选当前页面编码 --> <select onchange='jumpPage(this);'> <c:forEach var="i" begin="1" end="${totalPage}"> <option value="${i}" <c:if test="${currentPage == i}"> selected </c:if> >第${i}页</option> </c:forEach> </select> 输入页码:<input type="text" value="${currentPage}" id="jumpPageBox" size="3"> <input type="button" value="跳转" onclick="jumpPage(document.getElementById('jumpPageBox'))"> </pre> * @return */ public String getPageFormJumpHtml() { String s = "转到\n" + "\t <!-- 输出 HTML SELECT 元素, 并选当前页面编码 -->\n" + " <select onchange='jumpPage(this);'>\n" + " \n"; for(int i = 1; i <= getTotalPage(); i++ ) { s += "<option value=" + i + "\n"; if(currentPage == i) { s+= " selected "; } s += "\t>第" + i + "页</option>\n"; } s+= " </select>\n" + " 输入页码:<input type=\"text\" value=\"" + currentPage + "\" id=\"jumpPageBox\" size=\"3\"> \n" + " <input type=\"button\" value=\"跳转\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\"> "; return s; } /** * 进行分页计算. */ private void calculate() { if (getPageCount() == 0) { setPageCount(1); } totalPage = (int) Math.ceil(1.0 * getRecordCount() / getPageCount()); // 总页面数 if (totalPage == 0) totalPage = 1; // Check current page range, 2006-08-03 if(currentPage > totalPage) { currentPage = totalPage; } // System.out.println("currentPage=" + currentPage); // System.out.println("maxPage=" + maxPage); // // Fixed logic error at 2004-09-25 hasNextPage = currentPage < totalPage; hasPrevPage = currentPage > 1; return; } /** * @return Returns the 最大页面数. */ public int getTotalPage() { calculate(); return totalPage; } /** * @param currentPage * The 最大页面数 to set. */ @SuppressWarnings("unused") private void setTotalPage(int maxPage) { this.totalPage = maxPage; } /** * 是否有上一页数据 */ public boolean hasPrevPage() { calculate(); return hasPrevPage; } /** * 是否有下一页数据 */ public boolean hasNextPage() { calculate(); return hasNextPage; } // Test public static void main(String[] args) { PageBean pc = new PageBean(); pc.setCurrentPage(2); pc.setPageCount(4); pc.setRecordCount(5); pc.setPageUrl("product/list.do"); System.out.println("当前页 " + pc.getCurrentPage()); System.out.println("有上一页 " + pc.hasPrevPage()); System.out.println("有下一页 " + pc.hasNextPage()); System.out.println("总页面数 " + pc.getTotalPage()); System.out.println("分页 HTML 代码 " + pc.getPageJumpLinkHtml()); } /** * @return Returns the 当前页码数. */ public int getCurrentPage() { return currentPage; } /** * 设置当前页码, 从 1 开始. * @param currentPage * The 当前页码数 to set. */ public void setCurrentPage(int currentPage) { if (currentPage <= 0) { currentPage = 1; } this.currentPage = currentPage; } /** * @return Returns the recordCount. */ public int getRecordCount() { return recordCount; } /** * @param recordCount * The recordCount to set. */ public void setRecordCount(int property1) { this.recordCount = property1; } /** * @return Returns the 每页显示记录数. */ public int getPageCount() { return pageCount; } /** * @param pageCount * The 每页显示记录数 to set. */ public void setPageCount(int pageCount) { this.pageCount = pageCount; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String value) { pageUrl = value; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值