import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FormDataServlet")
public class FormDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// 获取表单数据
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
// 创建响应内容
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Form Data Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Form Data</h1>");
out.println("<p>First Name: " + firstName + "</p>");
out.println("<p>Last Name: " + lastName + "</p>");
out.println("</body>");
out.println("</html>");
}
}
在这个例子中,假设有一个包含两个字段(firstName 和 lastName)的 HTML 表单。通过 request.getParameter 方法,我们可以获取这两个字段的值,并在响应中显示出来。
请确保 HTML 表单的 action 属性指向这个 Servlet,并且使用 POST 方法提交表单数据。
例如,HTML 表单可能如下所示:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action="/your-context-root/FormDataServlet" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
请替换 "/your-context-root/" 为你实际的应用程序上下文路径。在这个例子中,通过提交表单,数据将被发送到 FormDataServlet,在 Servlet 中我们获取这些数据并生成一个包含用户输入的响应。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6874/Servlet