编写一个Java类和一个JSP页面,把下列信息封装到3个Student对象里,再把每一个对象放到一个ArrayList对象里,再利用ArrayList对象在JSP页面的表格中显示所示的信息,如图所示。
时间: 2024-09-10 22:12:12 浏览: 55
为了实现这个需求,我们需要创建一个Java类`Student`,一个包含`ArrayList<Student>`的JavaServlet或Controller,以及相应的JSP页面用于显示数据。这里是一个简单的示例:
**Java Class (Student.java)**:
```java
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private String major;
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
// Getters and Setters...
}
```
**Java Servlet/Controller (MyServlet.java or MyController.java)**:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;
@WebServlet("/students")
public class MyServlet extends HttpServlet {
private ArrayList<Student> studentsList = new ArrayList<>();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Add some sample students to the list
studentsList.add(new Student("张三", 20, "计算机科学"));
studentsList.add(new Student("李四", 22, "软件工程"));
studentsList.add(new Student("王五", 19, "人工智能"));
// Pass the list to the JSP for rendering
request.setAttribute("students", studentsList);
RequestDispatcher rd = request.getRequestDispatcher("displayStudents.jsp");
rd.forward(request, response);
}
}
```
**JSP Page (displayStudents.jsp)**:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>学生列表</title>
</head>
<body>
<table border="1">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>专业</th>
</tr>
<% for (Student student : (ArrayList<Student>) request.getAttribute("students")) { %>
<tr>
<td><%= student.getName() %></td>
<td><%= student.getAge() %></td>
<td><%= student.getMajor() %></td>
</tr>
<% } %>
</table>
</body>
</html>
```
这个JSP页面会遍历传入的`students`列表,并将每个学生的属性显示在一个表格中。
阅读全文