分页查询思路
问题: 服务器向浏览器想用数据很多的时候可以对数据进行封装。
domain层 封装数据
package com.baidu.domain; import java.util.List; public class PageBean {
//总页数
private int totalPage;
//总条数
private int totalCount;
//数据集合
private List<Product> list;
//当前页
private int currPage;
//页数显示信息数
private int pageSize;
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<Product> getList() {
return list;
}
public void setList(List<Product> list) {
this.list = list;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
} }
浏览器只需要使用项服务器发送页数,服务器会发送pageBean对象进行返回。
Service层 处理业务
public PageBean getPageListProduct(int currPage) throws Exception {
PageBean pb=new PageBean();
//设置页面数
pb.setPageSize(10);
pb.setCurrPage(currPage);
//获取集合列表
List<Product> list = pd.getPageListProduct(pb); pb.setList(list);
for (Product product : pb.getList()) {
System.out.println(product);
}
//获取总条数
int l = (int) pd.getPageProductAcount();
pb.setTotalCount(l);
//获取总页数
if (l%10==0) {
pb.setTotalPage(l/10);
}else{
pb.setTotalPage((l/10)+1);
}
return pb; }
dao层
public List<Product> getPageListProduct(PageBean pb) throws SQLException {
QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
String sql="select * from product limit ?,?";
List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class),(pb.getCurrPage()-1)*pb.getPageSize(),pb.getPageSize());
return list;
}
public long getPageProductAcount() throws SQLException {
QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
String sql="Select count(*) from product";
long l = (Long)qr.query(sql, new ScalarHandler());
return l; }
JDBCUtils
public class JDBCUtils {
private static final ComboPooledDataSource cpd=new ComboPooledDataSource(); /**
* 获取连接对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
Connection conn = cpd.getConnection();
return conn;
}
/**
* 获取数据源
* @return
*/
public static DataSource getDataSource(){
return cpd;
}
}