分页并不难,只要想清楚了就好了。通常有两种方式(至少我知道两种):
1. 数据库分页:
/**
* @param pageItems:每页显示多少条记录
* @param currentPage:当前页码
* @autor godelegant
*/
public List findAll(int pageItems, int currentPage){
StringBuffer sqlStr = new StringBuffer("SELECT * FROM Product LIMIT ?, ?");
// ...
// 首先需要计算出SQL语句中的起始位置和结束位置 startIndex 和 endIndex
int startIndex = (currentPage-1)*pageItems;
int endIndex = startIndex + pageItems;
db.getPstmt().setInt(1, startIndex);
db.getPstmt().setInt(2, endIndex);
ResultSet rs = db.getPstmt().executQuery();
// (假设你已经得到了数据库连接)
// 以上为MYSQL的JDBC分页,下面是ORACLE的,唯一不同的就是SQL语句而已
StringBuffer sqlStr = new StringBuffer("SELECT *, ROWNUM rn FROM (SELECT * FROM Product) WHERE rn < ?");
db.getPstmt().setInt(1, endIndex);
// ...
}2. 应用程序内存分页:
// ...
// 如果一次性列出所有的记录可能对系统存在很大的负担,我们可以采用应用程序内存分页的方式
// 首先将所有记录都查询出来,存放在内存中,然后再返回指定页码内的记录即可
// 这种方式比较简单,但是需要注意内存占用问题
public List findAll(int pageItems, int currentPage){
List result = new ArrayList();
// 先查询出所有的记录
List allProduct = productDao.getAll();
if(allProduct != null && !allProduct.isEmpty()){
// 按照分页规则返回指定页码的记录
int startIndex = (currentPage-1)*pageItems;
int endIndex = Math.min(startIndex + pageItems, allProduct.size());
for(int i=startIndex; i