今天花了很大的功夫写了一个完整的分页例子,希望贴出来与大家共享,我想我的设计思想还是不错的.有不对的地方请大家指出,我就不写那么详细了,如果你有Struts基础看了就明白。本程序在MyEclipse 上开发,数据库采用了mysql 4.0版,顺利通过测试
package com.pdw.bo;
import java.util.*;
import com.pdw.page.*;
public interface ProvinceBO {
public List searchProvince(String earchText,Pager pager) throws Exception;
public int getProvinceRowCount()throws Exception ;
}
package com.pdw.bo;
import java.util.*;
import com.pdw.page.Pager;
import com.pdw.dao.*;
public class ProvinceBoImpl implements ProvinceBO{
public List searchProvince(String earchText, Pager pager) throws Exception {
List result=new ArrayList();
//因为mysql支持select 分页,做我们需要在此构构出完整的sql语句
pager.setStr_query("select * from citys");
pager.setStr_query(pager.getStr_query()+" limit "+pager.getStartRow()+","+pager.getPageSize()+" ");
try{
result=new ProvinceDAO().provinceSearch(pager);
}catch(Exception e){
throw e;
}
return result;
}
public int getProvinceRowCount()throws Exception {
return new ProvinceDAO().getProvinceRowCount();
}
}
以上两个类是BO层的类
==============================================
package com.pdw.dao;
import java.sql.*;
import java.util.*;
import com.pdw.page.*;
import com.pdw.dbutil.*;
public class ProvinceDAO {
public List provinceSearch(Pager pager) throws Exception {
List province_list=new ArrayList();
DBConnection dbconn=DBConnection.getInstance();
Connection conn=dbconn.getConnection();
String str_query=pager.getStr_query();
try {
Statement stmt=conn.createStatement();
ResultSet rec=stmt.executeQuery(str_query);
while(rec.next()){
String str_temp=rec.getString("name");
province_list.add(str_temp);
}
rec.close();
stmt.close();
conn.close();
System.out.println("已取得记录");
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
return province_list;
}
public int getProvinceRowCount()throws Exception{
int result=0;
DBConnection dbconn=DBConnection.getInstance();
Connection conn=dbconn.getConnection();
try {
Statement stmt=conn.createStatement();
ResultSet rec=stmt.executeQuery("select * from citys");
while(rec.next()){
result=result+1;
}
rec.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
}
return result;
}
}
这是DAO的类
===========================================
package com.pdw.page;
import javax.servlet.http.HttpServletRequest;
public class PageHelper {
public Pager getPager(HttpServletRequest request,int totalRows){
//定义pager对象用于传到页面
Pager pager=new Pager(totalRows);
//从servlet中获取当前页号
String currentpage=request.getParameter("currentPage");
if(currentpage!=null)
pager.refersh(Integer.parseInt(currentpage));
String pagerMethod=request.getParameter("pageMethod");
if(pagerMethod!=null){
if(pagerMethod.equals("first"))
pager.first();
if(pagerMethod.equals("previous"))
pager.previous();
if(pagerMethod.equals("next"))
pager.next();
if(pagerMethod.equals("last"))
pager.last();
}
return pager;
}
}
package com.pdw.page;
/**
*
* @author Administrator
*
* TODO Pager类用于记录当前浏览的是第几页
*
*/
public class Pager {
private int totalRows; //总行数
private int pageSize=10; //每页显示的行数
private int currentPage; //当前页
private int totalPages; //总页数
private int startRow; //当前页在数据中的起始行
private String str_query; //查询的条件,通常条件是由BO层生成再保存到些,因为
//SQL的查询只返回当前页所需要的数据
public Pager(){
}
public Pager(int _totalrows){
this.totalRows=_totalrows;
this.totalPages=this.totalRows/pageSize;
int mod=totalRows % pageSize;
if(mod>0)
totalPages++;
currentPage=1;
startRow=0;
}
/**
* @return Returns the currentPage.
*/
public int getCurrentPage() {
return currentPage;
}
/**
* @param currentPage The currentPage to set.
*/
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
/**
* @return Returns the pageSize.
*/
public int getPageSize() {
return pageSize;
}
/**
* @param pageSize The pageSize to set.
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* @return Returns the startRow.
*/
public int getStartRow() {
return startRow;
}
/**
* @param startRow The startRow to set.
*/
public void setStartRow(int startRow) {
this.startRow = startRow;
}
/**
* @return Returns the totalPages.
*/
public int getTotalPages() {
return totalPages;
}
/**
* @param totalPages The totalPages to set.
*/
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
/**
* @return Returns the totalRows.
*/
public int getTotalRows() {
return totalRows;
}
/**
* @param totalRows The totalRows to set.
*/
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public String getStr_query() {
return str_query;
}
public void setStr_query(String str_query) {
this.str_query = str_query;
}
public void first(){
this.currentPage=1;
this.startRow=0;
}
public void previous(){
if(currentPage==1)
return;
currentPage--;
startRow=(currentPage-1)*pageSize;
}
public void next(){
if(currentPage<totalPages)
currentPage++;
startRow=(currentPage-1)*pageSize;
}
/**
* <p>定位到最后一页</p>
*
*/
public void last(){
currentPage=totalPages;
startRow=(currentPage-1)*pageSize;
}
public void refersh(int _currentpage){
currentPage=_currentpage;
if(currentPage>totalPages)
last();
}
}
这两个类是很分页的关键类,其中Pager是页面相关信息类,类里的数据变换是通过PageHelper来实现变转了。是根据请求的url的相应的参数来变换当前页,每一次请求就执行PageHelper 里的一个方法来确定当前第几页,以及这一页的记录从第几行开始。
===============================================
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.1/xslt/JavaClass.xsl
package com.pdw.structs;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.pdw.page.*;
import com.pdw.bo.*;
import java.util.*;
/**
* MyEclipse Struts
* Creation date: 01-05-2006
*
* XDoclet definition:
* @struts.action parameter="method"
* @struts.action-forward name="ok" path="/test.jsp"
*/
public class SpliPageDAction extends DispatchAction {
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward searchCitys(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ProvinceBO pbo=new ProvinceBoImpl();
try{
int rowcount=pbo.getProvinceRowCount();
PageHelper ph=new PageHelper();
Pager pager=ph.getPager(request,rowcount); //构造当前页和指定从N到M条记录的记录
List dataList=pbo.searchProvince("测试",pager);
request.setAttribute("dataList",dataList);
request.setAttribute("pager",pager);
}catch(Exception e){
throw e;
}
return mapping.findForward("ok");
}
}
//这是一个分页请求的action,一看就明天,通过该类你应该可以看到,不到的Action如果其需要分类实际要上做的工作就是把一次请求的总行数放进来构造一个Pager既可,至于查询的条件,你就需要在BO层自己封装了,如上面所以的BO类一样。
===============================
<%@ page contentType="text/html;charset=gbk"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<%@ page import="com.pdw.dbutil.*"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>测试</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<%--
DBConnection dbconn=DBConnection.getInstance();
Connection conn=dbconn.getConnection();
Statement stmt=conn.createStatement();
ResultSet rec=stmt.executeQuery("select * from province ");
while(rec.next()){
out.println(rec.getString("name")+"<br>");
}
rec.close();
dbconn.closeConnection(conn);
--%>
<logic:present name="dataList" scope="request">
<logic:iterate name="dataList" id="xlist">
<bean:write name="xlist"/><br>
</logic:iterate>
</logic:present>
<br>
<logic:present name="pager" scope="request">
<table width="770" height="19" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td class="s5" align="right"><div class="a1">
共<bean:write name="pager" property="totalPages"/>页
第<bean:write name="pager" property="currentPage"/>页
<html:link action="/spliPageDAction.do?method=searchCitys&pageMethod=first" paramName="pager" paramProperty="currentPage" paramId="currentPage" >首页</html:link>
<html:link action="/spliPageDAction.do?method=searchCitys&pageMethod=previous" paramName="pager" paramProperty="currentPage" paramId="currentPage" >上一页</html:link>
<html:link action="/spliPageDAction.do?method=searchCitys&pageMethod=next" paramName="pager" paramProperty="currentPage" paramId="currentPage" >下一页</html:link>
<html:link action="/spliPageDAction.do?method=searchCitys&pageMethod=last" paramName="pager" paramProperty="currentPage" paramId="currentPage" >最后一页</html:link>
</div></td>
</tr>
</table>
</logic:present>
</body>
</html:html>
这是我的一个分页程序的页面例子。你自己思考一下就能弄明白。
=========================================
我表达能力较差,不知你是否能看得明天,希望你看后能有所收获,如果什么错误的地方欢迎你指正。很晚了,差不多1点了,累了,睡休息了。。。