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

Java Servlet MVC:如何在JSP表格中展示数据库查询结果

没问题,我来帮你解决这个展示学生列表的问题!你已经完成了Bean、DAO和Servlet的核心逻辑,只差最后两步:把数据传递到JSP,以及在JSP里遍历生成表格行。

第一步:修改Servlet传递学生列表

你只需要在Servlet中把查询到的studentList存入request域,这样转发到JSP时就能携带这份数据。修改后的Servlet代码如下:

package com.mvc.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.bean.StudentBean;
import com.mvc.dao.StudentDao;
public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public StudentServlet() { }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StudentDao studentDao = new StudentDao();
        ArrayList<StudentBean> studentList = studentDao.getStudent();
        
        // 关键:将学生列表存入request域,属性名"studentList"用来在JSP中识别
        request.setAttribute("studentList", studentList);
        
        request.getRequestDispatcher("/Student.jsp").forward(request, response);
    }
}

第二步:修改JSP遍历数据生成表格

在JSP中,你需要先获取request域中的学生列表,然后遍历每个StudentBean对象,生成对应的表格行。同时要注意导入必要的类,避免编译错误。修改后的JSP代码如下:

<%@ page import="java.util.ArrayList" %>
<%@ page import="com.mvc.bean.StudentBean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student</title>
</head>
<body>
<!-- 添加border让表格更清晰,可选 -->
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<%
// 从request域中获取学生列表,注意强制类型转换
ArrayList<StudentBean> studentList = (ArrayList<StudentBean>) request.getAttribute("studentList");

// 空判断:避免数据库无数据或查询出错时出现空指针异常
if(studentList != null && !studentList.isEmpty()){
    // 遍历每个学生对象,生成表格行
    for(StudentBean student : studentList){
%>
<tr>
<td><%= student.getId() %></td>
<td><%= student.getName() %></td>
</tr>
<%
    }
} else {
%>
<tr>
<td colspan="2">没有找到学生数据</td>
</tr>
<%
}
%>
</table>
</body>
</html>

额外推荐:使用JSTL标签优化JSP(更规范)

如果想减少JSP中的Java脚本,符合MVC最佳实践,可以使用JSTL标签库:

  1. 先在项目中引入JSTL的jar包
  2. 在JSP顶部添加标签库声明:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  3. 替换表格部分代码为:
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<c:if test="${not empty studentList}">
    <c:forEach items="${studentList}" var="student">
    <tr>
        <td>${student.id}</td>
        <td>${student.name}</td>
    </tr>
    </c:forEach>
</c:if>
<c:if test="${empty studentList}">
<tr>
    <td colspan="2">没有找到学生数据</td>
</tr>
</c:if>
</table>

这样代码更简洁易读,也避免了JSP中嵌入过多Java逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:26