Servlet處理get請求時的中文亂碼問題


我們都知道,使用Servlet處理get請求時,如果get請求的參數中有中文,直接接收會是亂碼,這個時候我們使用類似下面的語句來處理亂碼:

1
2
3
4
5
String name = request.getParameter("name");
System.out.prinlnt(name); // 亂碼
// 處理亂碼
name = new String(name.getBytes("ISO8859-1"),"UTF-8");
System.out.println(name);// 亂碼問題解決

這時候每次中文都要處理,比較麻煩,我們可能會使用過濾器,使用類型下面的代碼處理亂碼問題:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null)
return null;
String method = request.getMethod();
if ("get".equalsIgnoreCase(method)) {
try {
value = new String(value.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return value;
}

但是,這是為什么呢?為什么我們需要將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_COMPLIANCE system property is set to true in which case ISO-8859-1 will be used.

那么也就意味着,從tomcat8.0開始,get請求中的中文參數,不需要特殊處理了。而如果是tomcat8之前的項目要遷移到tomcat8上面來,則也需要特殊注意這個問題,可能要刪減代碼中響應亂碼的處理模塊了。


免責聲明!

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



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