1. 按照如下图示使用表单标签创建一个jsp页面info.jsp。 2. 创建两个servlet程序,分别通过get和post方法获取请求并展示接收到的学生信息(学生信息示例如下,学生信息填写自己的信息即可)。
时间: 2024-10-29 11:14:25 浏览: 25
创建一个名为`info.jsp`的JSP页面,通常会包含HTML表单元素,用于收集用户输入的信息。以下是简单的`info.jsp`的代码示例:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>学生信息表单</title>
</head>
<body>
<form action="StudentInfoServlet" method="post">
<label for="name">姓名:</label><br>
<input type="text" id="name" name="studentName"><br>
<label for="age">年龄:</label><br>
<input type="number" id="age" name="studentAge"><br>
<label for="email">邮箱:</label><br>
<input type="email" id="email" name="studentEmail"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
```
这里我们创建了一个简单的表单,当用户点击提交按钮后,数据将通过POST方法发送到名为`StudentInfoServlet`的服务器端。
接下来,创建两个名为`StudentInfoGetServlet.java`和`StudentInfoPostServlet.java`的Servlet程序:
1. `StudentInfoGetServlet.java` (通过GET方法接收):
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class StudentInfoGetServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取查询参数,如 studentName、studentAge 和 studentEmail
String studentName = request.getParameter("studentName");
int studentAge = Integer.parseInt(request.getParameter("studentAge"));
String studentEmail = request.getParameter("studentEmail");
// 将数据展示到响应中,这里只是一个简略示例,实际应用中可以存储或处理这些数据
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<h1>Student Information:</h1>");
out.println("<p>Name: " + studentName + "</p>");
out.println("<p>Age: " + studentAge + "</p>");
out.println("<p>Email: " + studentEmail + "</p>");
}
}
```
2. `StudentInfoPostServlet.java` (通过POST方法接收):
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class StudentInfoPostServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取表单字段值
String studentName = request.getParameter("studentName");
int studentAge = Integer.parseInt(request.getParameter("studentAge"));
String studentEmail = request.getParameter("studentEmail");
// 同样地,这里仅作示例,实际应用中可以做数据库操作等
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<h1>Received Student Information:</h1>");
out.println("<p>Name: " + studentName + "</p>");
out.println("<p>Age: " + studentAge + "</p>");
out.println("<p>Email: " + studentEmail + "</p>");
}
}
```
注意,你需要配置这两个Servlet,并将其映射到相应的URL路径,例如`/StudentInfoServlet`和`/StudentInfoPostServlet`。同时,别忘了在web.xml文件中注册它们。
阅读全文