servlet,实现方法 后台分页

赵永恩


1、首先是在后台查询出每页的条数,然后封装,在页面显示。
2、相应代码


<%@ page contentType="text/html; charset=utf-8" language="java" import="com.cpt.ygc.entity.*"%>
<%@ page import = "com.cpt.ygc.db.*,com.cpt.ygc.service.*,javax.sql.*,java.util.*"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@page isELIgnored="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>分页</title>
<script type="text/javascript">
function doQuery(){
formName.actionType.value="doQuery";
formName.submit();
}
</script>
</head>
<%
request.setCharacterEncoding("UTF-8");
String zykclassid_id=(String)session.getAttribute("zykclassid_id");
int zykclassid=Integer.parseInt(zykclassid_id);//类型id
int zyktype=0;//状态
int pageNo=0;
int pageper=10;
String zykqikansearchword=(String)session.getAttribute("zykqikansearchword");
int i=0;

try{
//可以通过参数pageno获得用户选择的页码
pageNo = Integer.parseInt(request.getParameter("pageno") );
}catch(Exception ex){
//默认为第一页
pageNo=1;
}
ZykQikanService columns=new ZykQikanService();
RowSetPage myBean=columns.getAllQikan(zykqikansearchword,zykclassid,zyktype,pageNo,pageper);
request.setAttribute("empPage", myBean);
%>
<body >

<!----------------------------------->
<%
RowSetPage empPage = (RowSetPage)request.getAttribute("empPage");
if (empPage == null ) empPage = RowSetPage.EMPTY_PAGE;
%>

<table width="774" border="0">
<tr>
<td valign="top">
<form name="formName" id="formName" method="post" action="">
<input type=hidden name=actionType>
<input type="hidden" name="method" id="method" value="">
<input type="hidden" name="changetype" id="changetype" value="">
<input type="hidden" name="forwordjsp" id="forwordjsp" value="">
<table width="574" border="0">
<tr>
<td colspan="5">当前位置:期刊库 </td>
</tr>
<tr>
<td style="font-weight: bolder;"><a href="/zyk/zykqikan/index.jsp" style="color: red;">新搞</a></td>
<td><a href="/zyk/zykqikan/waitcheck.jsp">待审核</a></td>
<td><a href="/zyk/zykqikan/public.jsp">已发布</a></td>
<td><a href="/zyk/zykqikan/garbage.jsp">回收站</a></td>
<td> </td>
</tr>
<tr>
<td><a href="#" onclick="check()">全选</a></td>
<td colspan="2">标题</td>
<td>上传时间</td>
<td>上传用户</td>
</tr>

<%RowSet empRS = (RowSet) empPage.getRowSet();
if (empRS!=null) while (empRS.next() ) {
%>
<tr>
<td><input type="checkbox" name="checkbox" value="<%=empRS.getString("qikanid")%>" > </td>
<td colspan="2"><a href="/zyk/zykqikan.do?method=chooseOneqikan&changetype=look&qikanid=<%=empRS.getString("qikanid")%>"><%=empRS.getString("title")%></a></td>
<td><%=empRS.getString("zyktime") %></td>
<td><%=empRS.getString("people") %></td>
</tr>
<%
i++;
}
%>
<tr><td colspan="5"> <%= empPage.getHTML("doQuery", "pageno")%> </td></tr>
</table>


<!------------------------------------------->

</body>
</html>




package com.cpt.ygc.db;

import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


/**
*
* 赵永恩
*
* Title: 分页对象<br>
* Description: 用于包含数据及分页信息的对象<br>
* Page类实现了用于显示分页信息的基本方法,但未指定所含数据的类型,
* 可根据需要实现以特定方式组织数据的子类,<br>
* 如RowSetPage以RowSet封装数据,ListPage以List封装数据<br>
*/
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()<this.getTotalPageCount());
}

/**
* 是否有上一页
* @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 "<input type='hidden' name='"+pageNoParamName+"' value='1' >";
}
if (queryJSFunctionName == null || queryJSFunctionName.trim().length()<1) {
queryJSFunctionName = "gotoPage";
}
if (pageNoParamName == null || pageNoParamName.trim().length()<1){
pageNoParamName = "pageno";
}

String gotoPage = "_"+queryJSFunctionName;
//String gotoPage = queryJSFunctionName;

StringBuffer html = new StringBuffer("\n");
html.append("<script language=\"Javascript1.2\">\n")
.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( "</script> \n")
.append( "");
html.append( "<table border=0 cellspacing=0 cellpadding=0 align=center width=80%> \n")
.append( " <tr> \n")
.append( " <td align=left> \n");
html.append( " 共" ).append( getTotalPageCount() ).append( "页")

.append( " 记录\n").append(getTotalSize()).append( " 条")
.append( " </td> <td align=center> \n");
if (hasPreviousPage()){
html.append( "[<a href='javascript:").append(gotoPage)
.append("(") .append(1)
.append( ")'>首页</a>] \n");

}
else{
html.append( "[首页]\n");
}
if (hasPreviousPage()){
html.append( "[<a href='javascript:").append(gotoPage)
.append("(") .append(getCurrentPageNo()-1)
.append( ")'>上一页</a>] \n");
}
else{
html.append( "[上一页]\n");
}
if (hasNextPage()){
html.append( " [<a href='javascript:").append(gotoPage)
.append("(").append((getCurrentPageNo()+1))
.append( ")'>下一页</a>] \n");
}
else{
html.append( "[下一页]\n");
}
if (hasNextPage()){
html.append( " [<a href='javascript:").append(gotoPage)
.append("(").append(getTotalPageCount())
.append( ")'>尾页</a>] \n");
}
else{
html.append( "[尾页]\n");
}
html.append( "   跳转")
.append( " <input id='").append(pageNoParamName).append("' name= '")
.append(pageNoParamName).append("' type='text' size='1' onkeypress='javascript:if(event.keyCode==13){")
.append(gotoPage).append("(this.value);}'>\n");

html.append( " 页 \n")
.append("<a href='#' onclick='javascript:")
.append(gotoPage).append("(document.getElementById(\"").append(pageNoParamName).append("\").value);")
.append("return false;'>Go</a>\n");
html.append( "</td></tr></table> \n");
return html.toString();

}
}




package com.cpt.ygc.db;

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;

/**
* <p>Title: 分页查询</p>
* <p>Description: 根据查询语句和页码查询出当页数据</p>
*/
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;
DBConnect dbc = null;

/**
* 构造一查询出所有数据的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");
try{
dbc = new DBConnect();
}
catch(Exception e){
e.printStackTrace();
}
Connection conn =dbc.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");
try{
dbc.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

/**
*将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;
}
}

}



package com.cpt.ygc.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.RowSet;
import oracle.jdbc.rowset.OracleCachedRowSet;

/**
* <p>Title: 分页查询Oracle数据库实现</p>
*/
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(startIndex + size)
.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;
}

}




package com.cpt.ygc.db;

import javax.sql.RowSet;


/**
* <p>Title: RowSetPage</p>
* <p>Description: 使用RowSet封装数据的分页对象</p>
*/

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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值