1设计一个Servlet接收表单,表单内容包括:学号、姓名、性别、爱好,“提交”按钮、“取消”按钮输出为网页,2寻找表单传来的所有变量并输出在另一个网页
时间: 2024-10-15 21:23:22 浏览: 32
创建一个Servlet来接收用户通过表单提交的数据,首先需要设置HTML表单并在Servlet端进行处理。以下是步骤:
**1. 创建HTML表单(index.jsp)**
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>学生信息表单</title>
</head>
<body>
<form action="submitForm" method="post">
<label for="studentId">学号:</label>
<input type="text" id="studentId" name="studentId"><br><br>
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br><br>
<label for="gender">性别:</label>
<select id="gender" name="gender">
<option value="male">男</option>
<option value="female">女</option>
</select><br><br>
<label for="hobby">爱好:</label>
<textarea id="hobby" name="hobby"></textarea><br><br>
<input type="submit" value="提交">
<input type="button" value="取消" onclick="window.history.back()">
</form>
</body>
</html>
```
**2. 创建Servlet (SubmitFormServlet.java)**
```java
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class SubmitFormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取表单数据
String studentId = request.getParameter("studentId");
String name = request.getParameter("name");
String gender = request.getParameter("gender");
String hobby = request.getParameter("hobby");
// 将数据保存到Session或数据库,这里仅作示例,实际应用中会持久化数据
HttpSession session = request.getSession();
session.setAttribute("studentInfo", new StudentInfo(studentId, name, gender, hobby));
// 设置响应头,跳转到结果页面
response.sendRedirect("result.jsp");
}
}
class StudentInfo {
private String studentId;
private String name;
private String gender;
private String hobby;
// 构造函数等...
}
```
**3. 创建显示结果的JSP页面 (result.jsp)**
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>提交结果</title>
</head>
<body>
<%@ page import="com.example.StudentInfo" %>
<h2>用户信息:</h2>
<p>学号:${session.getAttribute("studentInfo").studentId}</p>
<p>姓名:${session.getAttribute("studentInfo").name}</p>
<p>性别:${session.getAttribute("studentInfo").gender}</p>
<p>爱好:${session.getAttribute("studentInfo").hobby}</p>
<!-- 显示数据 -->
</body>
</html>
```
在这个例子中,当用户点击“提交”按钮,表单数据会被发送到`SubmitFormServlet`,然后显示在`result.jsp`页面上。
阅读全文