首页 技术 正文
技术 2022年11月13日
0 收藏 542 点赞 2,307 浏览 1545 个字

之前关于编码的问题已经总结过两次了,有些地方写的很粗略。
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/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295