通过getParameter( “name” )方法获取页面参数时,当页面参数输入为中文的时候,获取到的中文参数会出现乱码问题
- get方式:提交不会出现乱码,因为tomcat内部已经解决了该问题
- post方式:会出现乱码
解决方法:
设置流的字符编码格式,因为使用post请求的时候,把请求体包装成了流,需要设置和前端口页面一样的字符编码格式,这时候需要用到request.setCharacterEncoding(“utf-8”)
代码如下:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/test04")
public class test04_Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
System.out.println(username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试中文乱码</title>
</head>
<body>
<form action="/test04" method="post">
姓名:<input type="text" placeholder="请输入姓名" name="username">
<br>
密码:<input type="text" placeholder="请输入密码" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
运行结果如下: