servlet 用post方式做表单
时间: 2023-06-12 16:08:09 浏览: 44
使用POST方式提交表单数据到Servlet需要以下步骤:
1. 在HTML表单中使用POST方法。
```html
<form method="post" action="servlet-url">
<!-- form fields -->
<input type="submit" value="提交">
</form>
```
2. 在Servlet中重写doPost方法来处理POST请求。
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取表单数据
String username = request.getParameter("username");
String password = request.getParameter("password");
// 处理表单数据
// ...
// 返回响应
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>表单提交成功</title></head>");
out.println("<body>");
out.println("<h1>表单提交成功</h1>");
out.println("<p>用户名:" + username + "</p>");
out.println("<p>密码:" + password + "</p>");
out.println("</body>");
out.println("</html>");
}
```
在doPost方法中,我们可以通过HttpServletRequest对象获取表单数据,对表单数据进行处理后再通过HttpServletResponse对象返回响应给客户端。在这个例子中,我们简单地将表单数据输出到HTML页面上。