mysql jsp分页技术_JSP分页技术实现

///

//

// Page.java

// author: evan_zhao@hotmail.com

//

///

package page;

import java.util.List;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Collections;

/**

* Title: 分页对象

* Description: 用于包含数据及分页信息的对象

* Page类实现了用于显示分页信息的基本方法,但未指定所含数据的类型,

* 可根据需要实现以特定方式组织数据的子类,

* 如RowSetPage以RowSet封装数据,ListPage以List封装数据

* Copyright: Copyright (c) 2002

* @author evan_zhao@hotmail.com

* @version 1.0

*/

public class Page implements java.io.Serializable {

public static final Page EMPTY_PAGE = new Page();

public static final int DEFAULT_PAGE_SIZE = 20;

public static final int MAX_PAGE_SIZE = 9999;

private int myPageSize = DEFAULT_PAGE_SIZE;

private int start;

private int avaCount,totalSize;

private Object data;

private int currentPageno;

private int totalPageCount;

/**

* 默认构造方法,只构造空页

*/

protected Page(){

this.init(0,0,0,DEFAULT_PAGE_SIZE,new Object());

}

/**

* 分页数据初始方法,由子类调用

* @param start 本页数据在数据库中的起始位置

* @param avaCount 本页包含的数据条数

* @param totalSize 数据库中总记录条数

* @param pageSize 本页容量

* @param data 本页包含的数据

*/

protected void init(int start, int avaCount, int totalSize, int pageSize, Object data){

this.avaCount =avaCount;

this.myPageSize = pageSize;

this.start = start;

this.totalSize = totalSize;

this.data=data;

//System.out.println("avaCount:"+avaCount);

//System.out.println("totalSize:"+totalSize);

if (avaCount>totalSize) {

//throw new RuntimeException("记录条数大于总条数?!");

}

this.currentPageno = (start -1)/pageSize +1;

this.totalPageCount = (totalSize + pageSize -1) / pageSize;

if (totalSize==0 && avaCount==0){

this.currentPageno = 1;

this.totalPageCount = 1;

}

//System.out.println("Start Index to Page No: " + start + "-" + currentPageno);

}

public Object getData(){

return this.data;

}

/**

* 取本页数据容量(本页能包含的记录数)

* @return 本页能包含的记录数

*/

public int getPageSize(){

return this.myPageSize;

}

/**

* 是否有下一页

* @return 是否有下一页

*/

public boolean hasNextPage() {

/*

if (avaCount==0 && totalSize==0){

return false;

}

return (start + avaCount -1) < totalSize;

*/

return (this.getCurrentPageNo()

}

/**

* 是否有上一页

* @return 是否有上一页

*/

public boolean hasPreviousPage() {

/*

return start > 1;

*/

return (this.getCurrentPageNo()>1);

}

/**

* 获取当前页第一条数据在数据库中的位置

* @return

*/

public int getStart(){

return start;

}

/**

* 获取当前页最后一条数据在数据库中的位置

* @return

*/

public int getEnd(){

int end = this.getStart() + this.getSize() -1;

if (end<0) {

end = 0;

}

return end;

}

/**

* 获取上一页第一条数据在数据库中的位置

* @return 记录对应的rownum

*/

public int getStartOfPreviousPage() {

return Math.max(start-myPageSize, 1);

}

/**

* 获取下一页第一条数据在数据库中的位置

* @return 记录对应的rownum

*/

public int getStartOfNextPage() {

return start + avaCount;

}

/**

* 获取任一页第一条数据在数据库中的位置,每页条数使用默认值

* @param pageNo 页号

* @return 记录对应的rownum

*/

public static int getStartOfAnyPage(int pageNo){

return getStartOfAnyPage(pageNo, DEFAULT_PAGE_SIZE);

}

/**

* 获取任一页第一条数据在数据库中的位置

* @param pageNo 页号

* @param pageSize 每页包含的记录数

* @return 记录对应的rownum

*/

public static int getStartOfAnyPage(int pageNo, int pageSize){

int startIndex = (pageNo-1) * pageSize + 1;

if ( startIndex < 1) startIndex = 1;

//System.out.println("Page No to Start Index: " + pageNo + "-" + startIndex);

return startIndex;

}

/**

* 取本页包含的记录数

* @return 本页包含的记录数

*/

public int getSize() {

return avaCount;

}

/**

* 取数据库中包含的总记录数

* @return 数据库中包含的总记录数

*/

public int getTotalSize() {

return this.totalSize;

}

/**

* 取当前页码

* @return 当前页码

*/

public int getCurrentPageNo(){

return this.currentPageno;

}

/**

* 取总页码

* @return 总页码

*/

public int getTotalPageCount(){

return this.totalPageCount;

}

/**

*

* @param queryJSFunctionName 实现分页的JS脚本名字,页码变动时会自动回调该方法

* @param pageNoParamName 页码参数名称

* @return

*/

public String getHTML(String queryJSFunctionName, String pageNoParamName){

if (getTotalPageCount()<1){

return "";

}

if (queryJSFunctionName == null || queryJSFunctionName.trim().length()<1) {

queryJSFunctionName = "gotoPage";

}

if (pageNoParamName == null || pageNoParamName.trim().length()<1){

pageNoParamName = "pageno";

}

String gotoPage = "_"+queryJSFunctionName;

StringBuffer html = new StringBuffer("\n");

html.append("

.append("function ").append(gotoPage).append("(pageNo){ \n")

.append( " var curPage=1; \n")

.append( " try{ curPage = document.all[\"")

.append(pageNoParamName).append("\"].value; \n")

.append( " document.all[\"").append(pageNoParamName)

.append("\"].value = pageNo; \n")

.append( " ").append(queryJSFunctionName).append("(pageNo); \n")

.append( " return true; \n")

.append( " }catch(e){ \n")

// .append( " try{ \n")

// .append( " document.forms[0].submit(); \n")

// .append( " }catch(e){ \n")

.append( " alert('尚未定义查询方法:function ")

.append(queryJSFunctionName).append("()'); \n")

.append( " document.all[\"").append(pageNoParamName)

.append("\"].value = curPage; \n")

.append( " return false; \n")

// .append( " } \n")

.append( " } \n")

.append( "}")

.append( " \n")

.append( "");

html.append( "

.append( "

\n")

.append( "


\n");

html.append( " 共" ).append( getTotalPageCount() ).append( "页")

.append( " [") .append(getStart()).append("..").append(getEnd())

.append("/").append(this.getTotalSize()).append("] \n")

.append( "

\n")

.append( "

\n");

if (hasPreviousPage()){

html.append( "[上一页] \n");

}

html.append( " 第")

.append( " \n");

String selected = "selected";

for(int i=1;i<=getTotalPageCount();i++){

if( i == getCurrentPageNo() )

selected = "selected";

else selected = "";

html.append( "

.append(selected).append(">").append(i).append("

\n");

}

if (getCurrentPageNo()>getTotalPageCount()){

html.append( " ").append(getCurrentPageNo())

.append(" \n");

}

html.append( " 页 \n");

if (hasNextPage()){

html.append( " [下一页] \n");

}

html.append( "

\n");

return html.toString();

}

}

///

//

// RowSetPage.java

// author: evan_zhao@hotmail.com

//

///

package page;

import javax.sql.RowSet;

/**

*

Title: RowSetPage

*

Description: 使用RowSet封装数据的分页对象

*

Copyright: Copyright (c) 2003

* @author evan_zhao@hotmail.com

* @version 1.0

*/

public class RowSetPage extends Page {

private javax.sql.RowSet rs;

/**

*空页

*/

public static final RowSetPage EMPTY_PAGE = new RowSetPage();

/**

*默认构造方法,创建空页

*/

public RowSetPage(){

this(null, 0,0);

}

/**

*构造分页对象

*@param crs 包含一页数据的OracleCachedRowSet

*@param start 该页数据在数据库中的起始位置

*@param totalSize 数据库中包含的记录总数

*/

public RowSetPage(RowSet crs, int start, int totalSize) {

this(crs,start,totalSize,Page.DEFAULT_PAGE_SIZE);

}

/**

*构造分页对象

*@param crs 包含一页数据的OracleCachedRowSet

*@param start 该页数据在数据库中的起始位置

*@param totalSize 数据库中包含的记录总数

*@pageSize 本页能容纳的记录数

*/

public RowSetPage(RowSet crs, int start, int totalSize, int pageSize) {

try{

int avaCount=0;

if (crs!=null) {

crs.beforeFirst();

if (crs.next()){

crs.last();

avaCount = crs.getRow();

}

crs.beforeFirst();

}

rs = crs;

super.init(start,avaCount,totalSize,pageSize,rs);

}catch(java.sql.SQLException sqle){

throw new RuntimeException(sqle.toString());

}

}

/**

*取分页对象中的记录数据

*/

public javax.sql.RowSet getRowSet(){

return rs;

}

}

///

//

// PagedStatement.java

// author: evan_zhao@hotmail.com

//

///

package page;

import foo.DBUtil;

import java.math.BigDecimal;

import java.util.List;

import java.util.Iterator;

import java.util.Collections;

import java.sql.Connection;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.PreparedStatement;

import java.sql.Timestamp;

import javax.sql.RowSet;

/**

*

Title: 分页查询

*

Description: 根据查询语句和页码查询出当页数据

*

Copyright: Copyright (c) 2002

* @author evan_zhao@hotmail.com

* @version 1.0

*/

public abstract class PagedStatement {

public final static int MAX_PAGE_SIZE = Page.MAX_PAGE_SIZE;

protected String countSQL, querySQL;

protected int pageNo,pageSize,startIndex,totalCount;

protected javax.sql.RowSet rowSet;

protected RowSetPage rowSetPage;

private List boundParams;

/**

* 构造一查询出所有数据的PageStatement

* @param sql query sql

*/

public PagedStatement(String sql){

this(sql,1,MAX_PAGE_SIZE);

}

/**

* 构造一查询出当页数据的PageStatement

* @param sql query sql

* @param pageNo 页码

*/

public PagedStatement(String sql, int pageNo){

this(sql, pageNo, Page.DEFAULT_PAGE_SIZE);

}

/**

* 构造一查询出当页数据的PageStatement,并指定每页显示记录条数

* @param sql query sql

* @param pageNo 页码

* @param pageSize 每页容量

*/

public PagedStatement(String sql, int pageNo, int pageSize){

this.pageNo = pageNo;

this.pageSize = pageSize;

this.startIndex = Page.getStartOfAnyPage(pageNo, pageSize);

this.boundParams = Collections.synchronizedList(new java.util.LinkedList());

this.countSQL = "select count(*) from ( " + sql +") ";

this.querySQL = intiQuerySQL(sql, this.startIndex, pageSize);

}

/**

*生成查询一页数据的sql语句

*@param sql 原查询语句

*@startIndex 开始记录位置

*@size 需要获取的记录数

*/

protected abstract String intiQuerySQL(String sql, int startIndex, int size);

/**

*使用给出的对象设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param obj 包含参数值的对象

*/

public void setObject(int index, Object obj) throws SQLException{

BoundParam bp = new BoundParam(index, obj);

boundParams.remove(bp);

boundParams.add( bp);

}

/**

*使用给出的对象设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param obj 包含参数值的对象

*@param targetSqlType 参数的数据库类型

*/

public void setObject(int index, Object obj, int targetSqlType) throws SQLException{

BoundParam bp = new BoundParam(index, obj, targetSqlType);

boundParams.remove(bp);

boundParams.add(bp );

}

/**

*使用给出的对象设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param obj 包含参数值的对象

*@param targetSqlType 参数的数据库类型(常量定义在java.sql.Types中)

*@param scale 精度,小数点后的位数

* (只对targetSqlType是Types.NUMBER或Types.DECIMAL有效,其它类型则忽略)

*/

public void setObject(int index, Object obj, int targetSqlType, int scale) throws SQLException{

BoundParam bp = new BoundParam(index, obj, targetSqlType, scale) ;

boundParams.remove(bp);

boundParams.add(bp);

}

/**

*使用给出的字符串设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param str 包含参数值的字符串

*/

public void setString(int index, String str)throws SQLException{

BoundParam bp = new BoundParam(index, str) ;

boundParams.remove(bp);

boundParams.add(bp);

}

/**

*使用给出的字符串设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param timestamp 包含参数值的时间戳

*/

public void setTimestamp(int index, Timestamp timestamp)throws SQLException{

BoundParam bp = new BoundParam(index, timestamp) ;

boundParams.remove(bp);

boundParams.add( bp );

}

/**

*使用给出的整数设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param value 包含参数值的整数

*/

public void setInt(int index, int value)throws SQLException{

BoundParam bp = new BoundParam(index, new Integer(value)) ;

boundParams.remove(bp);

boundParams.add( bp );

}

/**

*使用给出的长整数设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param value 包含参数值的长整数

*/

public void setLong(int index, long value)throws SQLException{

BoundParam bp = new BoundParam(index, new Long(value)) ;

boundParams.remove(bp);

boundParams.add( bp );

}

/**

*使用给出的双精度浮点数设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param value 包含参数值的双精度浮点数

*/

public void setDouble(int index, double value)throws SQLException{

BoundParam bp = new BoundParam(index, new Double(value)) ;

boundParams.remove(bp);

boundParams.add( bp);

}

/**

*使用给出的BigDecimal设置指定参数的值

*@param index 第一个参数为1,第二个为2,。。。

*@param bd 包含参数值的BigDecimal

*/

public void setBigDecimal(int index, BigDecimal bd)throws SQLException{

BoundParam bp = new BoundParam(index, bd ) ;

boundParams.remove(bp);

boundParams.add( bp);

}

private void setParams(PreparedStatement pst) throws SQLException{

if (pst==null || this.boundParams==null || this.boundParams.size()==0 ) return ;

BoundParam param;

for (Iterator itr = this.boundParams.iterator();itr.hasNext();){

param = (BoundParam) itr.next();

if (param==null) continue;

if (param.sqlType == java.sql.Types.OTHER){

pst.setObject(param.index, param.value);

}else{

pst.setObject(param.index, param.value, param.sqlType, param.scale);

}

}

}

/**

* 执行查询取得一页数据,执行结束后关闭数据库连接

* @return RowSetPage

* @throws SQLException

*/

public RowSetPage executeQuery() throws SQLException{

System.out.println("executeQueryUsingPreparedStatement");

Connection conn = DBUtil.getConnection();

PreparedStatement pst = null;

ResultSet rs = null;

try{

pst = conn.prepareStatement(this.countSQL);

setParams(pst);

rs =pst.executeQuery();

if (rs.next()){

totalCount = rs.getInt(1);

} else {

totalCount = 0;

}

rs.close();

pst.close();

if (totalCount < 1 ) return RowSetPage.EMPTY_PAGE;

pst = conn.prepareStatement(this.querySQL);

System.out.println(querySQL);

pst.setFetchSize(this.pageSize);

setParams(pst);

rs =pst.executeQuery();

//rs.setFetchSize(pageSize);

this.rowSet = populate(rs);

rs.close();

rs = null;

pst.close();

pst = null;

this.rowSetPage = new RowSetPage(this.rowSet,startIndex,totalCount,pageSize);

return this.rowSetPage;

}catch(SQLException sqle){

//System.out.println("executeQuery SQLException");

sqle.printStackTrace();

throw sqle;

}catch(Exception e){

e.printStackTrace();

throw new RuntimeException(e.toString());

}finally{

//System.out.println("executeQuery finally");

DBUtil.close(rs, pst, conn);

}

}

/**

*将ResultSet数据填充进CachedRowSet

*/

protected abstract RowSet populate(ResultSet rs) throws SQLException;

/**

*取封装成RowSet查询结果

*@return RowSet

*/

public javax.sql.RowSet getRowSet(){

return this.rowSet;

}

/**

*取封装成RowSetPage的查询结果

*@return RowSetPage

*/

public RowSetPage getRowSetPage() {

return this.rowSetPage;

}

/**

*关闭数据库连接

*/

public void close(){

//因为数据库连接在查询结束或发生异常时即关闭,此处不做任何事情

//留待扩充。

}

private class BoundParam {

int index;

Object value;

int sqlType;

int scale;

public BoundParam(int index, Object value) {

this(index, value, java.sql.Types.OTHER);

}

public BoundParam(int index, Object value, int sqlType) {

this(index, value, sqlType, 0);

}

public BoundParam(int index, Object value, int sqlType, int scale) {

this.index = index;

this.value = value;

this.sqlType = sqlType;

this.scale = scale;

}

public boolean equals(Object obj){

if (obj!=null && this.getClass().isInstance(obj)){

BoundParam bp = (BoundParam)obj;

if (this.index==bp.index) return true;

}

return false;

}

}

}

///

//

// PagedStatementOracleImpl.java

// author: evan_zhao@hotmail.com

//

///

package page;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.sql.RowSet;

import oracle.jdbc.rowset.OracleCachedRowSet;

/**

*

Title: 分页查询Oracle数据库实现

*

Copyright: Copyright (c) 2002

* @author evan_zhao@hotmail.com

* @version 1.0

*/

public class PagedStatementOracleImpl extends PagedStatement {

/**

* 构造一查询出所有数据的PageStatement

* @param sql query sql

*/

public PagedStatementOracleImpl(String sql){

super(sql);

}

/**

* 构造一查询出当页数据的PageStatement

* @param sql query sql

* @param pageNo 页码

*/

public PagedStatementOracleImpl(String sql, int pageNo){

super(sql, pageNo);

}

/**

* 构造一查询出当页数据的PageStatement,并指定每页显示记录条数

* @param sql query sql

* @param pageNo 页码

* @param pageSize 每页容量

*/

public PagedStatementOracleImpl(String sql, int pageNo, int pageSize){

super(sql, pageNo, pageSize);

}

/**

*生成查询一页数据的sql语句

*@param sql 原查询语句

*@startIndex 开始记录位置

*@size 需要获取的记录数

*/

protected String intiQuerySQL(String sql, int startIndex, int size){

StringBuffer querySQL = new StringBuffer();

if (size != super.MAX_PAGE_SIZE) {

querySQL.append("select * from (select my_table.*,rownum as my_rownum from(")

.append( sql)

.append(") my_table where rownum

.append(") where my_rownum>=").append(startIndex);

} else {

querySQL.append("select * from (select my_table.*,rownum as my_rownum from(")

.append(sql)

.append(") my_table ")

.append(") where my_rownum>=").append(startIndex);

}

return querySQL.toString();

}

/**

*将ResultSet数据填充进CachedRowSet

*/

protected RowSet populate(ResultSet rs) throws SQLException{

OracleCachedRowSet ocrs = new OracleCachedRowSet();

ocrs.populate(rs);

return ocrs;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值