🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
核心代码 web ~~~ //分页查询 public void queryCategoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1 调用service中的查询方法 try { String tmp=request.getParameter("currentPage"); String tmp1=request.getParameter("currentCount"); int currentPage = Integer.parseInt(tmp);//当前页 int currentCount = Integer.parseInt(tmp1);//当前总数 //没参数设置为第一页 // 给分页数据设置默认值 if (currentCount==0){ currentCount=5; } if (currentPage==0){ currentPage=1; } CategoryService service=new CategoryService(); Page page = service.findPageCategory(currentPage, currentCount); if (page!=null) { request.setAttribute("page",page); request.getRequestDispatcher("/category-list.jsp").forward(request,response); } else { request.getRequestDispatcher("/category-list.jsp").forward(request,response); } } catch (SQLException e) { e.printStackTrace(); } } ~~~ service ~~~ //分页查询 public Page findPageCategory(int currentPage, int currentCount) throws SQLException { Page page=new Page(); // 1 查询出生鲜数据的总数 CategoryDao dao = new CategoryDao(); int totalCount = dao.queryCount(); /* 总数 每页显示数目 总页数 9 10 0.9 1 10 10 1 1 11 10 1.1 2 java ceil */ // 2 根据总数和当前页显示数 计算出总页数 int totalPage= (int) Math.ceil(1.0*totalCount/currentCount); //3 将分页相关信息封装到page类中 page.setCurrentCount(currentCount); page.setCurrentPage(currentPage); page.setTotalCount(totalCount); page.setTotalPage(totalPage); // 计算查询的起始位置 // 页数 每页显示条数 起始位置 // // 1 3 0 // 2 3 3 // 3 3 6 (currentPage-1)*currentCount //计算出起始位置 int startPosition=(currentPage-1)*currentCount; // 分页查询数据 List<Category> categories = dao.queryPageCategoryList(startPosition,currentCount); // 将集合数据封装到page类中 page.setList(categories); return page; } ~~~ dao ~~~ //分页查询 public List<Category> queryPageCategoryList(int startPosition, int currentCount) throws SQLException { ComboPooledDataSource dataSource=new ComboPooledDataSource(); QueryRunner queryRunner=new QueryRunner(dataSource); String sql="select * from category limit ?,?"; List<Category> categoryList = queryRunner.query(sql, new BeanListHandler<Category>(Category.class),startPosition,currentCount); return categoryList; } ~~~ 前端 ~~~ <!--分页 --> <nav> <ul class="pagination pull-right"> <li class="previous"><a href="#">&laquo;</a></li> <c:forEach begin="1" end="${page.totalPage}" var="Page"> <li><a href="${pageContext.request.contextPath}/category?method=queryCategoryList&currentPage=${Page}&currentCount=5">${Page}</a></li> </c:forEach> <li><a href="#">&raquo;</a></li> </ul> </nav> ~~~ 结果 ![](https://box.kancloud.cn/ef77b59ee9769793598a25e60f87a1d8_1585x814.png)