以下是一个简单的JSP代码,用于浏览学生信息:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息</title>
</head>
<body>
    <h1>学生信息列表</h1>
    <table>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        <% 
            // 这里假设有一个名为students的List对象,其中包含学生信息
            List<Student> students = (List<Student>) request.getAttribute("students");
            for(Student student : students) {
        %>
        <tr>
            <td><%= student.getId() %></td>
            <td><%= student.getName() %></td>
            <td><%= student.getAge() %></td>
            <td><%= student.getGender() %></td>
        </tr>
        <% } %>
    </table>
</body>
</html>

请注意,上述代码中假设有一个名为students的List对象,其中包含学生信息。你需要将这个对象设置为请求属性,然后在Servlet中将其传递给JSP页面。以下是一个示例Servlet代码:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/studentList")
public class StudentListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 创建一个包含学生信息的List对象
        List<Student> students = new ArrayList<>();
        students.add(new Student("001", "张三", 18, "男"));
        students.add(new Student("002", "李四", 19, "女"));
        students.add(new Student("003", "王五", 20, "男"));

        // 将students对象设置为请求属性
        request.setAttribute("students", students);

        // 转发到JSP页面
        request.getRequestDispatcher("/studentList.jsp").forward(request, response);
    }
}

上述示例中,Student是一个包含学生信息的自定义类,你可以根据自己的需求修改。在Servlet的doGet方法中,我们创建了一个students对象,并将其设置为请求属性。然后,我们通过request.getRequestDispatcher方法将请求转发到studentList.jsp页面。在该页面中,我们使用<%= %>表达式来输出学生信息表格的内容。

请注意,你需要根据你的项目结构和需求修改URL映射、类名和包名等。此外,你还需要在项目中添加相应的依赖库,例如Servlet API和JSTL库,以确保代码正常运行。

JavaWeb JSP 学生信息浏览代码示例 - 带Servlet数据传递

原文地址: https://www.cveoy.top/t/topic/mV8r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录