URIEncoding和useBodyEncodingForURI详解

之前关于编码的问题已经总结过两次了,有些地方写的很粗略。
http://blog.itpub.net/29254281/viewspace-775925/
http://blog.itpub.net/29254281/viewspace-1063133/

Tomcat解决请求乱码可以使用URIEncoding和useBodyEncodingForURI.下面是两个参数的具体说明,参见ApacheTomcat官方手册。

URIEncoding This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
useBodyEncodingForURI This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

URIEncoding和useBodyEncodingForURI详解
在上图可以看到,中文乱码容易出现在两个地方。一个是所请求的资源名称为中文,一个是查询参数的内容包括中文。
更复杂的是,不同的浏览器可能使用两种编码分别处理URL和查询参数。
useBodyEncodingForURI只是针对图上"author=君山"的查询参数(QueryString)有效,他的设置对于URL和URI无效。
下面以Windows环境为例,分别测试谷歌、火狐和IE浏览器请求中文资源和中文参数的乱码情况。

下表是三种浏览器的编码情况。其中IE的URI编码可以调整为UTF8。

  默认URI编码 默认查询参数编码
谷歌 UTF8 UTF8
火狐 UTF8 GBK
IE GBK GBK


1.Tomcat的URIEncoding设置为UTF8
谷歌正常
火狐可以请求到资源,但是查询参数的中文为乱码
IE不能请求到资源

测试代码如下
URIEncoding和useBodyEncodingForURI详解
测试结果如下:
URIEncoding和useBodyEncodingForURI详解

2.将IE的URI编码设置为UTF8,开启useBodyEncodingForURI,并设置request的字符集为GBK。
URIEncoding和useBodyEncodingForURI详解
针对URI和查询参数使用两种编码的情况,可以使用useBodyEncodingForURI。他会根据http body设置的字符集解码。
将IE设置为"发送UTF8的URL"之后,三种浏览器都使用UTF8作为URI编码,但是IE和火狐的查询参数使用GBK编码,而谷歌的查询参数使用UTF8编码。所以在这种情况下,IE和火狐的访问都是正常的,而使用谷歌浏览器,可以访问资源,但是中文的查询参数则是乱码。
URIEncoding和useBodyEncodingForURI详解
测试结果:
URIEncoding和useBodyEncodingForURI详解

实验得出的结论是
1.URIEncoding和useBodyEncodingForURI都可以处理中文乱码的问题
2.浏览器对于URI和查询参数可能使用两种不同的编码方式,这种情况下,可以使用useBodyEncodingForURI调整查询参数的编码。

参考:
http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/

上一篇:【转】关于B/S架构应用程序的权限设置分析和总结


下一篇:SQL Server 快速大数据排序方法