1、doGet()方法和doPost()方法获取请求参数的乱码问题
我们使用的tomcat是8.0.53版本
注意:tomcat8以后已经解决了get的乱码问题,7之前才需要进行编码转换。
a.post请求中文乱码问题分析
- post请求(数据在请求体中)参数是通过Request的getReader()来获取流中的数据。
- TOMCAT在获取流中的数据时采用的编码方式是IOS-8859-1
- 而IOS-8859-1并不支持中文,所以产生乱码显现。
解决方案:
- 把tomcat在获取数据流之前将数据的编码改为utf-8
- 通过request.setCharacterEncoding(“UTF-8”)设置编码,utf-8小写也可以。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取数据流之前将数据的编码改为utf-8
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
}
注意:若在request.setCharacterEncoding(“utf-8”);这句代码之前已经使用了getParameter()方法来获取参数,则设置编码就会失败。如下,就会出现乱码
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String password = request.getParameter("password");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
System.out.println(username);
}
b.get请求中文乱码问题分析
- get请求获取请求参数的方式是request.getQueryString();
- get请求没有请求体来存放请求内容,而是采用url上传输请求内容
- 浏览器在发送HTTP的过程中会对中文数据进行URL编码,在进行URL编码的时候会采用页面标签指定的UTF-8的方式进行编码,例如:张三的utf-8编码为%E5%BC%A0%E4%B8%89
- 后台服务器(tomcat)接收到%E5%BC%A0%E4%B8%89后会默认按照ISO-8859-1进行URL解码
- 由于前后编码与解码采用不一致,就会导致后台取到的数据乱码
总结:
- 浏览器把中文参数按照
UTF-8
进行URL编码 - Tomcat对获取到的内容进行了
ISO-8859-1
的URL解码 - 在控制台就会出现乱码
解决方案:
1.按照ISO-8859-1编码获取乱码对应的字节数组
2.按照UTF-8编码获取字节数组对应的字符串
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
//按照ISO-8859-1编码获取乱码对应的字节数组
byte[] bytes = username.getBytes("iso-8859-1");
//按照UTF-8编码获取字节数组对应的字符串
username = new String(bytes, "UTF-8");
System.out.println("用户名;"+username);
}