时间:2021-07-01 10:21:17 帮助过:4人阅读
其次,showUsers.jsp页面(有省略,且部分名修改)
<c:choose> <c:when test="${users != null }"> <br> <form action="#" method="post"> <table class="table table-striped table-bordered"> <thead> <tr> <td>ID</td> <td>NAME</td> <td>CODE</td> <td>PWD</td> <td>STATE</td> <td>FLAG</td> <td>Update</td> </tr> </thead> <c:forEach items="${users }" var="user"> <tr> <td>${user.id }</td> <td>${user.name }</td> <td>${user.code }</td> <td>${user.pwd }</td> <td>${user.state }</td> <td>${user.flag }</td> <td><a href="update.jsp?user=${user }">update</a></td> </tr> </c:forEach> </table> </form> <c:if test="${flag==‘T‘}"> <a href="<%=request.getContextPath()%>/showLimitUsers?currentRecord=${page.currentRecord}&type=prev">前一页</a> /<a href="<%=request.getContextPath()%>/showLimitUsers?currentRecord=${page.currentRecord}&type=next"> 后一页</a> </c:if>
.....
对于,servlet后台(SERVICE、DAO层代码省略...)
Page page = new Page(); UserService userService = new UserServiceImpl(); //去掉管理员 long totalRecord = userService.getUsersCount() - 1; page.setTotalRecord((int) totalRecord); page.setTotalPage(page.getTotalRecord(), page.getPageSize()); String type = request.getParameter("type"); if (request.getParameter("currentRecord") != null && !request.getParameter("currentRecord").equals("")) { int currentRecord = Integer.parseInt(request .getParameter("currentRecord")); page.setCurrentRecord(currentRecord); page.setCurrentPage(page.getCurrentRecord(), page.getPageSize()); if ("next".equals(type) && page.getCurrentPage() < (page.getTotalPage() - 1)) { currentRecord = currentRecord + 10; page.setCurrentRecord(currentRecord); } else if ("prev".equals(type) && page.getCurrentPage() > 0) { currentRecord = currentRecord - 10; page.setCurrentRecord(currentRecord); } } else { page.setCurrentRecord(0); } List<User> users = userService.getLimitUsers(page.getCurrentRecord(), page.getPageSize()); page.setCurrentPage(page.getCurrentRecord(), page.getPageSize()); HttpSession session = request.getSession(); //<a>标签是否显示 session.setAttribute("flag", "T"); session.setAttribute("users", users); session.setAttribute("page", page); response.sendRedirect(request.getContextPath() + "/showUsers.jsp");
当用户点击了next,当前记录数就加pageSize,prev则减去pageSize。同时当前页也需要与总页数之间进行比较,以防超越了页数范围。
由于未将所有功能均设置分页,故设定flag标志,当页面其他功能不需要分页的话,可以将分页<a>消除。
效果图:
PS:文中Page VO为借鉴而来。
心得:
分页不难,但还是会出现bug,需要好好调试。可以通过打印Page&将所传的值在input标签显示方便调试。
MySql 分页
标签: