我們都知道,使用Servlet處理get請求時,如果get請求的參數中有中文,直接接收會是亂碼,這個時候我們使用類似下面的語句來處理亂碼:
1 |
String name = request.getParameter("name"); |
這時候每次中文都要處理,比較麻煩,我們可能會使用過濾器,使用類型下面的代碼處理亂碼問題:
1 |
public String getParameter(String name) { |
但是,這是為什么呢?為什么我們需要將ISO8859-1轉為UTF-8?為什么我們接收到的參數是ISO8859-1這種編碼方式的?
其實很簡單,只是個配置問題:
在tomcat安裝目錄下的conf/server.xml中,有如下的配置:
1 |
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> |
我們可能改動過這里的port為9999,8888等自己喜歡的端口號,這里呢,也可以設置另外一個跟上述編碼問題有關的參數信息:URIEncoding,該配置決定了使用get請求通過瀏覽器地址欄訪問tomcat時的編碼方式,默認的編碼方式使ISO8859-1,這一點我們可以從官網文檔(https://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.
知道了這點,接下來就簡單了,我們可以這樣配置,則上述代碼中,就不需要再從ISO8859-1轉為UTF-8了:
1 |
URIEncoding="UTF-8" |
這顯然比上述兩種方式簡單多了。
值得注意的是,從tomcat8.0開始,URIEncoding默認值不再是ISO8859-1,而變成了UTF-8
官方文檔 (https://tomcat.apache.org/tomcat-8.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, UTF-8 will be used unless the
org.apache.catalina.STRICT_SERVLET_COMPLIANCEsystem property is set totruein which case ISO-8859-1 will be used.
那么也就意味着,從tomcat8.0開始,get請求中的中文參數,不需要特殊處理了。而如果是tomcat8之前的項目要遷移到tomcat8上面來,則也需要特殊注意這個問題,可能要刪減代碼中響應亂碼的處理模塊了。
