鱼C论坛

 找回密码
 立即注册
查看: 121|回复: 5

为什么我的java web分页功能无法实现?

[复制链接]
发表于 2024-3-25 20:17:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我使用Servlet、Mybatis和JSP搭建了一个web项目,已经完成了查询功能的开发。现在想写一个分页查询功能,使用SQL的limite语句分页查询,初始化只查询前两个,之后通过点击前端的按钮来切换每页展示的信息。已知分页的selectByPage可以正常运行,但是点击了前端的按钮无法实现预期的分页功能。
  1. package edu.zjku.controller;

  2. import edu.zjku.bean.Blog;
  3. import edu.zjku.service.BlogService;
  4. import edu.zjku.service.BlogServiceImpl;

  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;
  11. import java.io.IOException;
  12. import java.util.List;

  13. //这是查询所有博客的Servlet
  14. @WebServlet("/selectServlet")
  15. public class SelectServlet extends HttpServlet {
  16.     private BlogService service = new BlogServiceImpl();

  17.     @Override
  18.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19.         //获取分页信息
  20.         String param = req.getParameter("pageNumber");
  21.         String param2 = req.getParameter("linesPerPage");
  22.         int pageNumber;
  23.         int linesPerPage;
  24.         try {
  25.             pageNumber = Integer.parseInt(param);
  26.             linesPerPage = Integer.parseInt(param2);
  27.         } catch (NumberFormatException e) {
  28.             pageNumber = 1;
  29.             linesPerPage = 2;
  30.         }
  31.         //读取数据并封装
  32.         List<Blog> blogs = null;
  33.         blogs = service.selectByPage(pageNumber, linesPerPage);
  34.         //存入会话域给看博客页面使用
  35.         HttpSession session = req.getSession();
  36.         session.setAttribute("blogs", blogs);
  37.         //跳转到看博客页面
  38.         resp.sendRedirect("/theBlog/read.jsp");
  39.     }

  40.     @Override
  41.     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  42.         doGet(req, resp);
  43.     }
  44. }
复制代码
  1. <%@ page import="java.util.List" %>
  2. <%@ page import="edu.zjku.bean.Blog" %><%--
  3.   Created by IntelliJ IDEA.
  4.   User: xing
  5.   Date: 2024/3/20
  6.   Time: 20:58
  7.   To change this template use File | Settings | File Templates.
  8. --%>
  9. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  10. <html>
  11. <head>
  12.     <title>看博客</title>
  13.     <link rel="stylesheet" href="style/public.css">
  14.     <style>
  15.         .box p:nth-of-type(1) {
  16.             text-align: center;
  17.         }

  18.         .box p:nth-of-type(2) {
  19.             white-space: pre-wrap;
  20.         }

  21.         .box p:nth-of-type(3),
  22.         .box p:nth-of-type(4) {
  23.             text-align: right;
  24.         }
  25.     </style>
  26. </head>
  27. <body>
  28. <jsp:include page="header.jsp"/>
  29. <main>
  30.     <%
  31.         //从会话域获取所有博客
  32.         List<Blog> blogs = (List<Blog>) session.getAttribute("blogs");
  33.         //循环显示所有博客
  34.         for (Blog blog : blogs) {%>
  35.     <div class="box">
  36.         <p><%=blog.getTitle()%>
  37.         </p>
  38.         <p><%=blog.getText()%>
  39.         </p>
  40.         <p><%=blog.getUser()%>
  41.         </p>
  42.         <p><%=blog.getTime()%>
  43.         </p>
  44.     </div>
  45.     <%}%>
  46.     <%--        这是控制分页的控件--%>
  47.     <div class="page">
  48.         <button class="prev">上一页</button>
  49.         <button class="next">下一页</button>
  50.     </div>
  51. </main>
  52. <jsp:include page="footer.jsp"/>
  53. <script>
  54.     //这是控制分页的JS
  55.     //获取分页控件
  56.     let prev = document.querySelector(".page .prev");
  57.     let next = document.querySelector(".page .next");

  58.     //传递分页信息
  59.     let pageNumber = 1;
  60.     let linesPerPage = 2;

  61.     function prevPage() {
  62.         pageNumber -= 1;
  63.         let url = `/theBlog/selectServlet?pageNumber=${pageNumber}linesPerPage=${linesPerPage}`;
  64.         axios.get(url)
  65.             .then(function (response) {
  66.                 console.log(response);
  67.             })
  68.             .catch(function (error) {
  69.                 console.log(error);
  70.             })
  71.             .finally(function () {
  72.                 console.log("运行结束!");
  73.             })
  74.     }

  75.     function nextPage() {
  76.         pageNumber += 1;
  77.         let url = `/theBlog/selectServlet?pageNumber=${pageNumber}linesPerPage=${linesPerPage}`;
  78.         axios.get(url)
  79.             .then(function (response) {
  80.                 console.log(response);
  81.             })
  82.             .catch(function (error) {
  83.                 console.log(error);
  84.             })
  85.             .finally(function () {
  86.                 console.log("运行结束!");
  87.             })
  88.     }

  89.     //添加响应事件
  90.     prev.addEventListener("click", prevPage);
  91.     next.addEventListener("click", nextPage);
  92. </script>
  93. </body>
  94. </html>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-3-25 20:17:48 | 显示全部楼层
在你提供的代码中,我注意到了一些问题。首先,你的分页链接缺少了一个“&”符号,导致无法正确传递两个参数(pageNumber和linesPerPage)。其次,你的Servlet只是重定向到了一个JSP页面,但是并没有将查询结果传递给JSP页面进行展示。因此,在点击前端按钮后,你并没有看到分页的效果。

为了解决这个问题,你可以按照以下步骤进行操作:

1. 修改分页链接:
在你的JS文件中,将分页链接的url修改为:
`let url = `/theBlog/selectServlet?pageNumber=${pageNumber}&linesPerPage=${linesPerPage}`;`

2. 修改Servlet:
在Servlet的doGet方法中,将查询结果封装成一个JSON对象,并传递给JSP页面。修改的代码如下:
  1. //读取数据并封装
  2. List<Blog> blogs = service.selectByPage(pageNumber, linesPerPage);
  3. //将查询结果封装成JSON对象
  4. JSONObject json = new JSONObject();
  5. json.put("blogs", blogs);
  6. json.put("pageNumber", pageNumber);
  7. json.put("linesPerPage", linesPerPage);
  8. //将JSON对象存入请求域中
  9. req.setAttribute("result", json);
  10. //跳转到看博客页面
  11. req.getRequestDispatcher("/theBlog/read.jsp").forward(req, resp);
复制代码


3. 修改JSP页面:
在read.jsp页面中,使用EL表达式获取请求域中的JSON对象,并根据需要展示分页的内容。修改的代码如下:
  1. <%
  2.     JSONObject result = (JSONObject) request.getAttribute("result");
  3.     List<Blog> blogs = (List<Blog>) result.get("blogs");
  4.     int pageNumber = (int) result.get("pageNumber");
  5.     int linesPerPage = (int) result.get("linesPerPage");
  6. %>
  7. <!-- 在这里根据自己的需求展示分页内容,可以使用JSTL标签库进行循环遍历 -->
复制代码


通过以上修改,你应该可以实现分页功能了。希望对你有所帮助!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-25 20:42:36 | 显示全部楼层
idea提示没有JSONObject这个类啊
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-25 20:42:48 | 显示全部楼层
ZhihanXing 发表于 2024-03-25 20:42
idea提示没有JSONObject这个类啊


抱歉,对不起给你带来困扰。在Java中,使用JSON对象需要引入相应的库。您可以使用第三方库,比如JSON.jar或者Gson等。下面是使用Gson库来完成JSON对象封装的代码示例:

  1. import com.google.gson.Gson;

  2. // 读取数据并封装
  3. List<Blog> blogs = service.selectByPage(pageNumber, linesPerPage);

  4. // 将查询结果封装成JSON对象
  5. Gson gson = new Gson();
  6. String jsonResult = gson.toJson(blogs);

  7. // 将JSON对象存入请求域中
  8. req.setAttribute("result", jsonResult);

  9. // 跳转到看博客页面
  10. req.getRequestDispatcher("/theBlog/read.jsp").forward(req, resp);
复制代码


然后,在JSP页面中通过EL表达式获取请求域中的JSON字符串,并将其转换为实际的对象:

  1. <%
  2.     String jsonResult = (String) request.getAttribute("result");
  3.     Gson gson = new Gson();
  4.     List<Blog> blogs = gson.fromJson(jsonResult, new TypeToken<List<Blog>>(){}.getType());
  5. %>

  6. <!-- 使用blogs进行展示 -->
复制代码


请确保已经正确导入Gson库,你可以在Maven项目中在pom.xml文件中添加以下依赖:

  1. <dependency>
  2.     <groupId>com.google.code.gson</groupId>
  3.     <artifactId>gson</artifactId>
  4.     <version>2.8.6</version>
  5. </dependency>
复制代码


希望这次能解决您的问题!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-25 20:43:38 | 显示全部楼层
我不能将其存入会话域然后在jsp读取吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-25 20:43:55 | 显示全部楼层
ZhihanXing 发表于 2024-03-25 20:43
我不能将其存入会话域然后在jsp读取吗?


当然可以将查询结果存入会话域中,然后在JSP页面中读取会话域的数据。以下是修改后的代码示例:在Servlet的doGet方法中,将查询结果存入会话域中://读取数据并封装List blogs = service.selectByPage(pageNumber, linesPerPage);//存入会话域给看博客页面使用HttpSession session = req.getSession();session.setAttribute("blogs", blogs);session.setAttribute("pageNumber", pageNumber);session.setAttribute("linesPerPage", linesPerPage);//跳转到看博客页面resp.sendRedirect("/theBlog/read.jsp");在JSP页面中,通过EL表达式读取会话域中的数据并进行展示: <%@ page language="java" contentType="text/html; charset=UTF-8"%><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>博客列表</title> </head> <body> <h1>博客列表</h1> <table> <thead> <tr> <th>ID</th> <th>标题</th> <th>内容</th> </tr> </thead> <tbody> <c:forEach var="blog" items="${sessionScope.blogs}"> <tr> <td>${blog.id}</td> <td>${blog.title}</td> <td>${blog.content}</td> </tr> </c:forEach> </tbody> </table> <div class="page"> <button class="prev" onclick="prevPage()">上一页</button> <button class="next" onclick="nextPage()">下一页</button> </div> <script src="your_script.js"></script> </body> </html>通过以上修改,您应该可以在JSP页面中展示分页查询的结果了。希望对您有所帮助!如有任何疑问,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 19:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表