先定义一个Student类(类中属性自行设置),然后在Servlet中实例化6个Student对象,将这6个对象存放到一个List集合中,然后将该List集合保存到request对象里,再将request请求转发到test.jsp,最后在test.jsp页面中利用JSTL+EL显示List集合中的6个Student对象的具体信息
时间: 2023-06-15 12:03:15 浏览: 101
调用抽象类中指定参数的构造方法-java课程ppt
好的,以下是示例代码:
```
// Student类定义
public class Student {
private String name;
private int age;
private String gender;
// 构造方法
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
```
在Servlet中实例化6个Student对象,并将它们添加到List集合中:
```
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Tom", 18, "male"));
studentList.add(new Student("Lucy", 20, "female"));
studentList.add(new Student("John", 19, "male"));
studentList.add(new Student("Lily", 21, "female"));
studentList.add(new Student("Mike", 22, "male"));
studentList.add(new Student("Sarah", 20, "female"));
// 将List集合保存到request对象中
request.setAttribute("studentList", studentList);
// 将请求转发到test.jsp
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
```
在test.jsp页面中利用JSTL+EL显示List集合中的6个Student对象的具体信息:
```
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test JSP</title>
</head>
<body>
<h1>Student List:</h1>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.name}</td>
<td>${student.age}</td>
<td>${student.gender}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
```
以上代码可以实现在JSP页面中显示List集合中的6个Student对象的具体信息。
阅读全文