You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Servlet无法展示两表关联查询的全部匹配结果问题排查

问题修复:JSP仅显示单条关联查询结果

你已经精准定位到了问题核心——在student_db_util的showcourse方法中,if(myRs.next())只会读取结果集的第一条记录,后续的匹配结果都被直接忽略了,这就是为什么JSP页面只显示一条数据的原因。

修复后的showcourse方法代码

public List<studentrgister> showcourse(String names) throws Exception {
    List<studentrgister> students = new ArrayList<>();
    String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
    System.out.println("loading the driver");
    Connection myConn = null;
    PreparedStatement ps = null;
    ResultSet myRs = null;
    
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("driver is loaded");
        myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
        System.out.println("username and password is correct");
        
        String sql = "SELECT mytest.firstName, class.name FROM mytest " +
                "INNER JOIN class ON mytest.id=class.id " +
                "WHERE mytest.firstName = ? ";
        ps = myConn.prepareStatement(sql);
        ps.setString(1, names);
        myRs = ps.executeQuery();
        
        // 用while循环遍历所有结果,替代原有的if只取第一条
        while (myRs.next()) {
            String classname = myRs.getString("name");
            studentrgister mystudent = new studentrgister(classname);
            students.add(mystudent);
        }
        
        // 无匹配结果时的友好提示(可根据业务需求调整逻辑)
        if(students.isEmpty()){
            throw new Exception("Could not find any courses for student: " + names);
        }
        
        return students;
    } finally {
        // 关闭实际使用的数据库资源,避免泄漏
        close(myConn, ps, myRs);
    }
}

额外的优化建议

  1. 移除Servlet中的重复调用:在seecourse方法里你重复调用了两次showcourse(names),删除其中一次即可:
private void seecourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String names=request.getParameter("names");
    // 移除这行重复的无效调用
    // student_db_util.showcourse(names);
    List<studentrgister> student=student_db_util.showcourse(names);
    request.setAttribute("mycourse", student);
    RequestDispatcher rd=request.getRequestDispatcher("/showcourse.jsp");
    rd.forward(request,response);
}
  1. 修正JSP表格结构:showcourse.jsp里的表格标签不规范,确保每条数据生成独立的表格行:
<body>
<table>
    <form action="studentregister" method="get">
        <input type="hidden" name="command" value="seecourse"/>
        <c:forEach var="tempstudent" items="${mycourse}">
            <tr>
                <td>${tempstudent.name}</td>
            </tr>
        </c:forEach>
    </form>
</table>
</body>
  1. 资源关闭的正确性:原代码finally块传入的myStmt是未初始化的空对象,替换为实际使用的PreparedStatement(即代码中的ps),避免潜在的数据库资源泄漏。

内容的提问来源于stack exchange,提问作者pooya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:57:31