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


在上圖可以看到,中文亂碼容易出現在兩個地方。一個是所請求的資源名稱為中文,一個是查詢參數的內容包括中文。
更復雜的是,不同的瀏覽器可能使用兩種編碼分別處理URL和查詢參數。
useBodyEncodingForURI只是針對圖上"author=君山"的查詢參數(QueryString)有效,他的設置對於URL和URI無效。
下面以Windows環境為例,分別測試谷歌、火狐和IE瀏覽器請求中文資源和中文參數的亂碼情況。

下表是三種瀏覽器的編碼情況。其中IE的URI編碼可以調整為UTF8。

  默認URI編碼 默認查詢參數編碼
谷歌 UTF8 UTF8
火狐 UTF8 GBK
IE GBK GBK


1.Tomcat的URIEncoding設置為UTF8
谷歌正常
火狐可以請求到資源,但是查詢參數的中文為亂碼
IE不能請求到資源

測試代碼如下

測試結果如下:


2.將IE的URI編碼設置為UTF8,開啟useBodyEncodingForURI,並設置request的字符集為GBK。

針對URI和查詢參數使用兩種編碼的情況,可以使用useBodyEncodingForURI。他會根據http body設置的字符集解碼。
將IE設置為"發送UTF8的URL"之后,三種瀏覽器都使用UTF8作為URI編碼,但是IE和火狐的查詢參數使用GBK編碼,而谷歌的查詢參數使用UTF8編碼。所以在這種情況下,IE和火狐的訪問都是正常的,而使用谷歌瀏覽器,可以訪問資源,但是中文的查詢參數則是亂碼。

測試結果:


實驗得出的結論是
1.URIEncoding和useBodyEncodingForURI都可以處理中文亂碼的問題
2.瀏覽器對於URI和查詢參數可能使用兩種不同的編碼方式,這種情況下,可以使用useBodyEncodingForURI調整查詢參數的編碼。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM