JSP分页查询

博客介绍了在JSP页面定义四个触发不同事件的按钮,之后在servlet中接收数据。利用分页数据为SQL语句占位符赋值以执行分页查询,最后需获取数据总行数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1)先是在JSP页面中定义四个按钮:

<button type="button" onclick="firstPage()">首页</button>
<button type="button" onclick="previousPage()">上一页</button>
<i >${currentPage} / ${totalPage }</i>
<button type="button" onclick="nextPage()">下一页</button>
<button type="button" onclick="lastPage()">尾页</button>

如图:
在这里插入图片描述
四个按钮分别触发不同事件:

//首页事件
function firstPage(){
window.location.href="${paths}/main";
}
//上一页事件
function previousPage(){
//当点击上一页按钮时就拿当前页减去1
currentPage = ${currentPage-1};
//判断当前页减去1后是否小于1,如果是则说明当前页就是第一页然后提示用户并结束方法
if(currentPage < 1){
layer.alert("已经是第一页了!", { icon: 0, title: '提示' });
return;
}
//如果当前页减去1后不小于1则把减去1后的当前页转发到servlet中
window.location.href="${paths}/main?currentPage="+currentPage;
}
//下一页
function nextPage(){
//当点击下一页按钮时就拿当前页加1
currentPage = ${currentPage+1};
//判断当前页加1后是否大于总页数,如果是则说明当前页就是最后一页了然后提示用户并结束方法
if(currentPage > '${totalPage}'){
layer.alert("已经是最后一页了!",{icon:0,title:'提示'});
return;
}
//如果当前页加1后不大于总页数则把加1后的当前页转发到servlet中
window.location.href="${paths}/main?currentPage="+currentPage;
}
//尾页
function lastPage(){
    //直接把总页数转发到servlet中
window.location.href="${paths}/main?currentPage="+${totalPage};
}

然后在servlet中接收这些数据

public void doPost(HttpServletRequest
request,HttpServletResponse response)throws ServletException,IOException{
//设置请求编码格式
request.setCharacterEncoding("utf-8");
//设置响应编码格式
response.setContentType("text/html;charset=utf-8");
//获取页面传来的当前分页
String currentPagestr = request.getParameter("currentPage");
//设置默认的当前分页
int currentPage = 1;
//设置默认的当前查询条数
int pageSize = 3;
//判断当前分页是否为空,不为空就转换成int类型
if(currentPagestr !=null){
currentPage = Integer.parseInt(currentPagestr);
}
//开始查询的位置 = (当前分页 -1) * 当前查询的条数
int startIndex = (currentPage-1)*pageSize;

//执行查询操作
IBorrowingService ibs = new BorrowingServiceImpl();
List<BorrowingPo> list = ibs.selectAllBorrowingAndPaging(startIndex, pageSize);

//获取总行数
int count = ibs.selectSumTotal();
//总页数 = 总行数 除于 当前的查询条数+1
int totalPage = count/pageSize+1;
//如果总行数 能整除 当前的查询条数 那么总页数就不加1
if(count%pageSize==0){
totalPage = count/pageSize;
}
request.setAttribute("currentPage", currentPage);//当前分页
request.setAttribute("count", count);//总行数
request.setAttribute("totalPage", totalPage);//总页数
request.setAttribute("list", list);
request.getRequestDispatcher("/jsp/MainJsp.jsp").forward(request, response);
}
在servlet中获取到分页数据后,接下来就要对数据库进行操作了
private String selectAllBorrowingAndPagingSQL = "select * from borrowing limit ?,?";

使用分页数据给上面SQL语句的占位符赋值后,就可以执行分页查询了,具体步骤就不演示了,最后还需要获取到数据的总行数。

private String selectSumTotalSQL = "select count(*) from borrowing";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值