分页查询思路
问题: 服务器向浏览器想用数据很多的时候可以对数据进行封装。
domain层 封装数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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层 处理业务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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层
1 2 3 4 5 6 | 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; } |
1 2 3 4 5 6 7 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步