JavaWeb入门之简单分页查询功能实现

一、MySql实现分页查询的SQL语句
1、分页需求:
客户端通过传递pageNo(页码),counter(每页显示的条数)两个参数去分页查询数据库表中的数据,那我们知道MySql数据库提供了分页的函数limit m,n,但是该函数的用法和我们的需求不一样,所以就需要我们根据实际情况去改写适合我们自己的分页语句,具体的分析如下:

比如:

查询第1条到第10条的数据的sql是:select * from table limit 0,10; ->对应我们的需求就是查询第一页的数据:select * from table limit (1-1)*10,10;

查询第10条到第20条的数据的sql是:select * from table limit 10,20; ->对应我们的需求就是查询第二页的数据:select * from table limit (2-1)*10,10;

查询第20条到第30条的数据的sql是:select * from table limit 20,30; ->对应我们的需求就是查询第三页的数据:select * from table limit (3-1)*10,10;

2、总结
通过上面的分析,可以得出符合我们自己需求的分页sql格式是:select * from table limit (pageNo-1)*counter,counter; 其中pageNo是页码,counter是每页显示的条数。

二、JavaWeb程序
1、创建PageBeanUtils.java工具类
package com.ambow.utils;
import java.util.List;
public class PageBeanUtils {
private int prePage;//上一页
private int nextPage;//下一页
private int firstPage=1;//首页
private int lastPage;//尾页
private int currentPage = 1;//当前
private int totalPage;//总页数
private int pageSize;//每页显示条数,默认显示10条
private int totalData;//数据总条数
private List pageData;//数据
public PageBeanUtils(int currentPage,int pageSize, int totalData) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalData = totalData;

//计算获得总页数(尾页)
// this.totalPage = this.lastPage = (totalData+pageSize-1)/pageSize;
this.totalPage = this.lastPage = (int)Math.ceil((double)totalData/pageSize);
//防止当前页小于1
this.currentPage = Math.max(this.currentPage, 1);
//防止当前页大于总的页数
this.currentPage = Math.min(this.totalPage, this.currentPage);
//设置上一页,上一页不能小于1
this.prePage = Math.max(this.currentPage-1, 1);
//设置下一页,下一页不能大于总页数
this.nextPage = Math.min(this.currentPage+1, this.totalPage);

/**

  • ceil
    public static double ceil(double a)
    返回最小的(最接近负无穷大) double 值,该值大于等于参数,并等于某个整数。特殊情况如下:
    如果参数值已经等于某个整数,那么结果与该参数相同。
    如果参数为 NaN、无穷大、正 0 或负 0,那么结果与参数相同。
    如果参数值小于 0,但是大于 -1.0,那么结果为负 0。
    注意, Math.ceil(x) 的值与 -Math.floor(-x) 的值完全相同。
    参数:
    a - 一个值。
    返回:
    最小(最接近负无穷大)浮点值,该值大于等于该参数,并等于某个整数。
    */

}

public PageBeanUtils(int prePage, int nextPage, int firstPage, int lastPage, int currentPage, int totalPage,
int pageSize, int totalData, List pageData) {
super();
this.prePage = prePage;
this.nextPage = nextPage;
this.firstPage = firstPage;
this.lastPage = lastPage;
this.currentPage = currentPage;
this.totalPage = totalPage;
this.pageSize = pageSize;
this.totalData = totalData;
this.pageData = pageData;
}
public int getPrePage() {
return prePage;
}
public void setPrePage(int prePage) {
this.prePage = prePage;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值