轉載:http://blog.itpub.NET/29254281/viewspace-1073278/
html
Tomcat解決請求亂碼能夠使用URIEncoding和useBodyEncodingForURI.下面是兩個參數的具體說明,參見ApacheTomcat官方手冊。java
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。apache
默認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/瀏覽器