您的位置:首页 > 运维架构 > Tomcat

tomcat6中文乱码解决过程及测试

2015-06-10 00:00 676 查看
摘要: tomcat传输内容乱码和conf/server.xml设置的编码有关,Connector节点中2个属性URIEncoding和useBodyEncodingForURI

项目中URL参数中一直传的是英文或数字,突然有一天发现传中文,出现乱码现象;

http://10.11.1.84:8080/test/index?resId=中国&resType=DISTRICT&result=xml

resId的值实际传入的是中文:中国

从网上搜索,发现tomcat5以后,可以通过修改tomcat的conf/server.xml配置,能解决中文乱码问题;

默认conf/server.xml的节点配置如下

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />

在此节点中,添加2个属性,可以设置内容编码:

URIEncoding

设置字符编码,如GBK、UTF-8、ISO-8859-1等

useBodyEncodingForURI

可以设置成true、false

设置成下面可以解决中文乱码问题

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true" />


为了弄清楚这2个参数对中文的影响,做了一系列测试。

tomcat版本:apache-tomcat-6.0.35

代码中对HttpServletRequest请求设置了CharacterEncoding属性

// HttpServletRequest request
String url = request.getRequestURL() + "?" + request.getQueryString();
logger.info("request url=" + url);

request.setCharacterEncoding("utf-8");
//request.setCharacterEncoding("gbk");
Map<String,String[]> map = request.getParameterMap();

Map<String,String> paramMap = new HashMap<String, String>();
for(String key:map.keySet()){
String[] values = map.get(key);
paramMap.put(key, values[0]);
}
logger.info("source params: " + paramMap);


下面是测试结果

在设置request.setCharacterEncoding("utf-8");时

useBodyEncodingForURI="true"
URIEncoding="UTF-8"    中文正常
URIEncoding="GBK"       中文正常
URIEncoding="ISO-8859-1"       中文正常

useBodyEncodingForURI="false"
URIEncoding="UTF-8"    中文正常
URIEncoding="GBK"       中文乱码
URIEncoding="ISO-8859-1"       中文乱码,和最初乱码一样

在设置request.setCharacterEncoding("gbk");时,都是乱码

结论:

tomcat传输内容乱码和conf/server.xml设置的编码有关,Connector节点中2个属性URIEncoding和useBodyEncodingForURI;

1)tomcat这2个参数默认值

URIEncoding="ISO-8859-1" useBodyEncodingForURI="false"

2)要中文不乱码

必要条件,useBodyEncodingForURI="true",且代码中设置HttpServletRequest.request.setCharacterEncoding("utf-8")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: