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";