URIEncoding和UseBodyEncodingForURI的解释

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

查阅官方文档,有如下表

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.

Notes: 1) This setting is applied only to the query string of a request. Unlike URIEncoding it does not affect the path portion of a request URI. 2) If request character encoding is not known (is not provided by a browser and is not set by SetCharacterEncodingFilter or a similar filter using Request.setCharacterEncoding method), the default encoding is always "ISO-8859-1". The URIEncoding setting has no effect on this default.


谷歌翻译:

URIEncoding

用指定的编码来解码uri中%xx那一部分字节,如果没有指定,默认为ISO-8859-1。如果uri中的中文不是经过EncodeURL编码转换成%xx的格式,而是普通的编码,即没有添加额外%字符的编码方式编码的,最后解码也是用ISO-8859-1

useBodyEncodingForURI

这指定contentType中指定的编码是否应用于URI查询参数,而不是使用URIEncoding。 此设置用于与Tomcat 4.1.x兼容,其中contentType中指定的编码或使用Request.setCharacterEncoding方法显式设置的编码也适用于来自URL的参数。 默认值为false。


注意:1)此设置仅应用于请求的查询字符串。 与URIEncoding不同,它不影响请求URI的路径部分。 2)如果请求字符编码未知(不是由浏览器提供,而不是由SetCharacterEncodingFilter或使用Request.setCharacterEncoding方法的类似过滤器设置),则默认编码始终为“ISO-8859-1”。 URIEncoding设置对此默认值没有影响。




用Chrome访问http://localhost:8081/Charset/CharsetServlet/君山?author=君山

通过F12查看

http://localhost:8081/Charset/CharsetServlet/%E5%90%9B%E5%B1%B1?author=%E5%90%9B%E5%B1%B1

通过分析发现uri中的中文和queryString中的中文都是utf-8编码的。我在其他浏览器firefox中测试发现uri和queryString的如果含有中文,仍然使用utf-8编码。但是我在阅读书籍和看别人博客发现,不同浏览器对uri和queryString这两部分的中文有不同的编码方式,比如uri是UTF-8编码,而queryString是GBK编码。我猜测应该是现在浏览器版本升级了统一了这两处的编码方式。


但是在实际应用中,我们仍然要知道uri和queryString这两部分的中文浏览器采用的编码方式可能不同。

而我们发送的HTTP请求通常有GET,POST

如果是采用get,最好是在tomcat的conf目录下找到servlet.xml:

1.设置URIEncoding="charsetName",服务器在对uri中的中文和 queryString的中文采用此指定的编码解码(前提是编码后的中文是%xx的形式,就是在编码后的每个字节前面还要加%的格式,例如EncodeURI后的值得格式),如果不是仍旧采用tomcat默认的iso-8859-1解码,所以这里有可能会产生乱码。

2.设置URIEncoding="cahrsetName" UseBodyEncodingForURI="true"。如果设置了UseBodyEncodingForURI为TRUE,就是对queryString的解码会采用请求头中content-type中指定的编码或者在request.setsetCharacterEncoding(charsetName)中指定的编码(默认这个方法只对post有用)。但是如果既没有content-type或者content-type中没有指定编码,并且没有通过request.setsetCharacterEncoding(charsetName)设置编码,默认还是会采用iso-8859-1解码queryString,所以这里也可能产生乱码


原文地址:https://www.cnblogs.com/chenny3/p/10226194.html