IDEA按照如下图示使用表单标签创建一个jsp页面info.jsp。创建两个servlet程序,分别通过get和post方法获取请求并展示接收到的学生信息(学生信息示例如下,学生信息填写自己的信息即可)给出具体的代码
时间: 2024-10-23 17:11:49 浏览: 39
在IntelliJ IDEA中,使用表单标签创建一个名为`info.jsp`的JSP页面,并配合Servlet处理GET和POST请求,你需要做以下几个步骤:
### 1. 创建JSP页面 (`info.jsp`)
```html
<!DOCTYPE html>
<html>
<head>
<title>学生信息</title>
</head>
<body>
<h2>请输入学生信息:</h2>
<form action="StudentInfoServlet" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">年龄:</label>
<input type="number" id="age" name="age"><br><br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
```
这里我们使用了HTML表单,将数据提交给名为`StudentInfoServlet`的Servlet。
### 2. 创建GET Servlet (`StudentInfoGetServlet.java`)
```java
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
public class StudentInfoGetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String email = request.getParameter("email");
// 在这里添加处理GET请求的逻辑,比如显示默认信息
String info = "Name: " + name + ", Age: " + age + ", Email: " + email;
response.getWriter().println("<p>Your GET information: " + info + "</p>");
}
}
```
### 3. 创建POST Servlet (`StudentInfoPostServlet.java`)
```java
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
public class StudentInfoPostServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// 获取请求参数
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String email = request.getParameter("email");
// 这里添加处理POST请求的逻辑,如存储数据或验证
String info = "Received POST data: Name - " + name + ", Age - " + age + ", Email - " + email;
response.getWriter().println("<p>Your submitted information: " + info + "</p>");
}
}
```
以上代码展示了如何在IntelliJ IDEA中创建一个包含表单的JSP页面,并用两个Servlet处理GET和POST请求。
阅读全文