getTest.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用POST</title>
</head>
<body>
<form action="HelloForm" method="POST">
用户名:<input type="text" name="user"><br>
密码:<input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
HelloForm.java
package request;
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("/HelloForm")
public class HelloForm extends HttpServlet {
public HelloForm() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
// 解决中文无法显示问题
String user = new String(req.getParameter("user").getBytes("iso-8859-1"), "utf-8");
String password = req.getParameter("password");
out.println("用户名为:" + user + "<br>");
out.println("密码为:" + password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
使用GET方式提交表单数据时,直接写String user = req.getParameter("user");也不会出现乱码。。。。