乱码的解决方案:
首先需要理解乱码的产生原因:无非就是编码格式的问题
1.服务器到浏览器
字节流传输时
产生乱码的原因:
1.浏览器打开方式不对(打开时 的方式为默认的方式,各个浏览器的方式都不同)
2.中文转字节数组
解决方案:
ServletOutputStream outputStream = response.getOutputStream();
response.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应头部
outputStream.write("成功".getBytes());
outputStream.close();
字符流传输时
产生乱码的原因:
字符流传输时是存在缓存区的,response获得字符流,
缓冲区中的默认编码格式为ISO-8859-1码,这个字符不支持中文;
解决方案1
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().print("中文1");
解决方案2
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("中文1");
2.浏览器到服务器乱码
乱码产生分为两类doGet和doPost
doGet乱码原因
浏览器——-url——-服务器
在请求时:数据在url中对数据进行了一次编码(ISO-8859-1);
浏览器—-(ISO-8859-1编码)—-url——-服务器
在传递的过程中都是使用字节传输的。
解决方案:
在服务器解决乱码:获取传递参数是先使用ISO-8859-1解码称为字节
再使用UTF-8进行重新编码
new String(request.getParameter(String name).getByte(“ISO-8859-1″),”UTF-8”);
doPost乱码原因
浏览器—–缓冲区(ISO-8859-1)—–服务器
只需要修改缓冲区编码格式就可以了
request.setCharacterEncoding(“UTF-8”);
3.编码格式转换
url进行编码
java.net.URLDecoder.decode(String s,String enc);
将application/x-www-form-urlencoded字符串转换成普通字符串。java.net.URLEncoder.decode(String s,String enc);
将普通字符串转换成application/x-www-form-urlencoded字符串。