首先新建实现分页工具类:
package com.servlet.product.util;
public class DividePageUtil {
private int pageSize;// 表示显示的条数
private int recordCount;// 表示记录的总条数
private int currentPage;// 表示当前页
public DividePageUtil(int pageSize, int recordCount, int currentPage) {
// TODO Auto-generated constructor stub
this.pageSize = pageSize;
this.recordCount = recordCount;
setCurrentPage(currentPage);
}
public DividePageUtil(int pageSize, int recordCount) {
// TODO Auto-generated constructor stub
this(pageSize, recordCount, 1);
}
// 获得总页数
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 int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
int validPage = currentPage <= 0 ? 1 : currentPage;
validPage = validPage > getPageCount() ? getPageCount() : validPage;
this.currentPage = validPage;
}
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;
}
}
在数据访问类中添加一个方法 来获得数据的总条数
public int getItemCount() {
int result = 0;
Map<String, Object> map = null;
String sql = " select count(*) mycount from product ";
try {
conn.getConnect();
map = conn.queryBySimpleResult(sql, null);
result = Integer.parseInt(map.get("mycount").toString());
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn.releaseConnect();
}
return result;
}
在数据处理类中来处理分类:
// 获得数据总条数
int recordCount = service.getItemCount();
// 当前页面 初始化为 1
int currentPage = 1;
// 获得当前页面
String pageNum = request.getParameter("pageNum");
if (pageNum != null) {
currentPage = Integer.parseInt(pageNum);
}
DividePageUtil util = new DividePageUtil(5, recordCount, currentPage);
//开始的条数
int start = util.getFromIndex();
//结束的条数
int end = util.getToIndex();
String proname = (String) request.getParameter("proname");
List<Map<String, Object>> list = service.listProduct(proname, start,
end);
request.setAttribute("util", util);
在jsp页面中使用javaScript来做处理:
function firstPage(){
var th=document.form1;
th.action="<%=path %>/servlet/ProductAction?action_flag=list&pageNum=1";
th.submit();
}
function forward(){
var th=document.form1;
th.action="<%=path %>/servlet/ProductAction?action_flag=list&pageNum=<%=util.getCurrentPage()-1%>";
th.submit();
}
function next(){
var th=document.form1;
th.action="<%=path %>/servlet/ProductAction?action_flag=list&pageNum=<%=util.getCurrentPage()+1%>";
th.submit();
}
function endPage(){
var th=document.form1;
th.action="<%=path %>/servlet/ProductAction?action_flag=list&pageNum=<%=util.getPageCount()%>";
th.submit();
}
function onChange(currentPage){
var th=document.form1;
th.action="<%=path %>/servlet/ProductAction?action_flag=list&pageNum="+currentPage;
th.submit();