1、GET请求
利用字符串构造方法,解决缓冲区中文乱码问题。
核心处理代码
String newString = new String(usr_name.getBytes("ISO8859-1"), "UTF-8");
实例:
// 处理响应的中文乱码
.setContentType("text/html;charset=utf-8");
response// 处理get请求发送过来的数据
String usr_name = request.getParameter("username");
// 解决缓冲区中文乱码
String newString = new String(usr_name.getBytes("ISO8859-1"), "UTF-8");
// 打印get缓冲区没处理的数据
.getWriter().print("没处理的数据:"+usr_name+"<br>");
response// 打印get缓冲区处理过的数据
.getWriter().print("处理完的数据:"+newString+"<br>"); response
测试:
2、POST请求
post方法发送过来的数据保存在reques缓冲区对象中,但是request对象默认使用ISO-8859-1
编码方式,不支持中文,所以会导致中文乱码。 解决方案
:
// 一定要写在处理之前!!!!!
.setCharacterEncoding("utf-8"); request
实例:
// 处理响应区乱码
.setContentType("text/html;charset=utf-8");
response// 处理缓冲区乱码
.setCharacterEncoding("utf-8");
request// 取到缓冲区的属性值
String post_name = request.getParameter("username");
// 打印
.getWriter().print(post_name); response
测试: