您的位置:首页 > 产品设计 > UI/UE

javaweb_day10(servlet&request&response)之乱码解决遍

2017-10-31 13:07 615 查看

servlet出现乱码的可能

乱码有三种:

1.get请求乱码

2.post请求乱码

3.response相应乱码

分析乱码的原因和解决:

【get请求】

分析原因:
当我们提交表单到服务器的时候,页面会先把表单的内容以
UTF-8的形式进行编码。然后得到的内容是utf-8的内容在发送给服务器,
服务器得到表单的内容是utf-8编码的内容,然后tomcat服务器拿到
内容之后通过iso-8859-1进行解码,这是乱码的根本原因。


原因



解决:

服务器拿到内容之后,先用is0-8859-1进行解码,然后在通过utf-8进行编码就能还远之前的内容。

具体解决:

方式一:先以iso-8895-1进行解码
//获取客户端传递过来的用户名参数值
String username = request.getParameter("username");
System.out.println("用户名:" + username);

// 先对用户名进行解码得到%E7%8E%8B%E6%8C%AF%E5%9B%BD 这样的形式
username = URLEncoder.encode(username, "ISO-8859-1");

// 再进行utf-8编码 一次得到页面上输入的文本内容
username = URLDecoder.decode(username, "UTF-8");
System.out.println("乱码解决后用户名:" + username);


方式二:

username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("乱码解决后用户名:" + username);


【post请求】

乱码原因:

因为post是以二进制流的形式发送到的服务器。服务器收到数据后。

默认以iso-8859-1进行编码。

POST请求乱码解决,只需要在获取请求参数之前调用

request.setCharacterEncoding(“UTF-8”); 方法设置字符集 即可。

解决方法:

// 1.post请求方式的数据是以二进制流的形式发送到服务器。
// 2.那么就说明它缺少一个字符集。所以我们要设置请求体的字符集即可。
// setCharacterEncoding必须要获取请求参数之前调用才有效
request.setCharacterEncoding("UTF-8");

//获取客户端传递过来的用户名参数值
String username = request.getParameter("username");
System.out.println("用户名:" + username);

}


【response相应】

服务器发给浏览器的数据默认是按照ISO-8859-1编码,浏览器接收到数据后按照默认的字符集进行解码后显示,如果浏览器的默认解码字符集不是ISO-8859-1,就出现乱码。
对于response乱码,只需要在服务器端指定一个编码字符集,然后通知浏览器按照这个字符集进行解码就可以了。有三种方式:
1、A、设置服务器端的编码
response.setCharacterEncoding("utf-8”);
默认是ISO-8859-1;该方法必须在response.getWriter()之前进行设置
B、通知浏览器服务器发送的数据格式
response.setHeader("contentType", "text/html; charset=utf-8”);
2、A、通知浏览器服务器发送的数据格式
response.setContentType("text/html;charset=utf-8”);
等同于response.setHeader("contentType", "text/html; charset=utf-8”);它其实会覆盖response.setCharacterEncoding("utf-8”) ,在开发中只需要设
B、设置服务器端的编码
response.setContentType("text/html;charset=utf-8”);
3、A、设置服务器端的编码
response.setCharacterEncoding("utf-8”);
B、浏览器使用utf-8进行解码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐