Servlet+JSP+MyBatis 分页插件实现首页、上一页、下一页、尾页功能
首先,需要在 pom.xml 文件中添加 MyBatis 分页插件的依赖:\nxml\n<dependency>\n <groupId>com.github.pagehelper</groupId>\n <artifactId>pagehelper</artifactId>\n <version>版本号</version>\n</dependency>\n\n\n然后,在 MyBatis 的配置文件中配置分页插件:\nxml\n<plugins>\n <plugin interceptor="com.github.pagehelper.PageInterceptor">\n <property name="helperDialect" value="数据库方言"/>\n <property name="reasonable" value="true"/>\n </plugin>\n</plugins>\n\n\n接下来,创建一个 Servlet 处理请求并将分页查询的结果传递给 JSP 页面:\njava\n@WebServlet("/index")\npublic class IndexServlet extends HttpServlet {\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n int pageNum = Integer.parseInt(request.getParameter("pageNum")); // 当前页码\n int pageSize = 10; // 每页显示的记录数\n\n // 调用 MyBatis 的分页查询方法,获取分页结果\n PageHelper.startPage(pageNum, pageSize);\n List<User> userList = userDao.getAllUsers(); // 自己定义的查询方法\n\n PageInfo<User> pageInfo = new PageInfo<>(userList);\n\n request.setAttribute("pageInfo", pageInfo);\n request.getRequestDispatcher("index.jsp").forward(request, response);\n }\n}\n\n\n在 JSP 页面中,使用 JSTL 标签库来展示分页信息和链接:\njsp\n<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>\n\n<!-- 显示记录列表 -->\n<c:forEach var="user" items="${pageInfo.list}">\n <tr>\n <td>${user.id}</td>\n <td>${user.name}</td>\n <td>${user.age}</td>\n </tr>\n</c:forEach>\n\n<!-- 显示分页导航 -->\n<ul class="pagination">\n <li><a href="index?pageNum=1">«</a></li>\n <c:if test="${pageInfo.hasPreviousPage}">\n <li><a href="index?pageNum=${pageInfo.pageNum - 1}"><</a></li>\n </c:if>\n <c:forEach var="pageNum" begin="${pageInfo.pageNum - 2}" end="${pageInfo.pageNum + 2}" step="1">\n <c:if test="${pageNum >= 1 && pageNum <= pageInfo.pages}">\n <c:choose>\n <c:when test="${pageNum eq pageInfo.pageNum}">\n <li class="active"><a href="#">${pageNum}</a></li>\n </c:when>\n <c:otherwise>\n <li><a href="index?pageNum=${pageNum}">${pageNum}</a></li>\n </c:otherwise>\n </c:choose>\n </c:if>\n </c:forEach>\n <c:if test="${pageInfo.hasNextPage}">\n <li><a href="index?pageNum=${pageInfo.pageNum + 1}">></a></li>\n </c:if>\n <li><a href="index?pageNum=${pageInfo.pages}">»</a></li>\n</ul>\n\n\n以上代码实现了在首页中显示记录列表和分页导航,可以通过点击导航链接实现上一页、下一页、首页和尾页的效果。
原文地址: https://www.cveoy.top/t/topic/p6Kr 著作权归作者所有。请勿转载和采集!