背景
一些基于Tomcat的传统Web项目,在Servlet
处理HttpServletRequest
和HttpServletResponse
的时候,如果未正确设置编码方式,中文内容在接收端往往表现为为乱码。
1、在GET请求中获取请求参数,中文乱码。
原因: Tomcat默认编码为iso-8859-1
。
几种处理方式:
- 直接进行转码:
String name = req.getParameter("name"); name = new String(name.getBytes("iso-8859-1"), "utf-8");
- 修改
tomcat/conf/server.xml
中的配置,设置URIEncoding="UTF-8"
:<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" URIEncoding="UTF-8" redirectPort="8443" />
- 或者设置
req.setCharacterEncoding("utf-8");
并且server.xml
的Connector节点添加属性useBodyEncodingForURI=true
。前者是设置采用utf-8编码方式来解析请求内容,后者是设置使用同样的编码方式来解析URI带的参数。
2、POST请求乱码
req.setCharacterEncoding("utf-8");
3、response乱码
resp.setCharacterEncoding("utf-8");
//或者
resp.setContentType("text/html;charset=utf-8");
注意,有时候直接设置resp.setCharacterEncoding("utf-8")
可能浏览器端并未识别编码格式,仍然展示乱码,换成gbk
却可以。
个中原因应该是:浏览器以设置的utf-8编码格式正确解析了服务端发回的响应,但是这个响应内容以什么样的编码方式在浏览器中进行显示呢? 如果不设置,浏览器默认采用gbk编码格式来展示响应内容,出现乱码。
这时候需要设置Content-Type来告诉浏览器该以什么编码格式来进行内容展示。
直接设置Content-Type:resp.setContentType("text/html;charset=utf-8")
一般就可以把解决问题了。
这一句要放在获取输出流(比如resp.getWriter())的代码之前,才会生效。
特别注意!!!
resp.setCharacterEncoding("utf-8");
和resp.setContentType("text/html;charset=utf-8");
的代码一定要放在获取输出流之前,比如要放在
PrintWriter writer=resp.getWriter();
之前。
否则,不会生效。