1、现一个Servlet,响应一个带有学生数据的表格
时间: 2023-06-03 09:04:06 浏览: 84
编写jsp页面实现如下界面效果,然后交给servlet计算矩形的周长和面积,并输出结果。
Sure, 这是一个Java Servlet代码的示例,用于响应一个带有学生数据的HTML表格:
```java
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;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// create some dummy student data
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("John Smith", "Computer Science", 3.8));
students.add(new Student("Jane Doe", "Mathematics", 3.5));
students.add(new Student("Joe Johnson", "History", 3.2));
// generate the HTML table
StringBuilder sb = new StringBuilder("<html><body><table><tr><th>Name</th><th>Major</th><th>GPA</th></tr>");
for (Student s : students) {
sb.append("<tr><td>").append(s.getName()).append("</td><td>").append(s.getMajor()).append("</td><td>").append(s.getGpa()).append("</td></tr>");
}
sb.append("</table></body></html>");
// write the HTML table to the response
response.setContentType("text/html");
response.getWriter().print(sb.toString());
}
}
class Student {
private String name;
private String major;
private double gpa;
public Student(String name, String major, double gpa) {
this.name = name;
this.major = major;
this.gpa = gpa;
}
public String getName() {
return name;
}
public String getMajor() {
return major;
}
public double getGpa() {
return gpa;
}
}
```
阅读全文