在Java Web開發中,http請求帶有中文字符的URI如果不處理容易出現亂碼問題;這是因為Tomcat容器默認編碼是iso-8859-1引起的,因此要避免出現亂碼就要需要做相應的處理。解決辦法如下:
一、在tomcat的 server.xml中設置
打開server.xml文件,對文件中設置如下:
在HTTP/1.1中增加URIEncoding="utf-8;
<Connector port="8098" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
---------------------------------------------------------------------------
...
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8098" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the BIO implementation that requires the JSSE
style configuration. When using the APR/native implementation, the
OpenSSL style configuration is required as described in the APR/native
documentation -->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
...
...
另外,若是使用的其它的容器,只需確認容器的默認編碼,做相應的設置即可。
二、配置servlet 可在服務程序中添加攔截器,當然也可用其它方式設置
示例:
public class CommonInterceptor implements Interceptor {
public void intercept(Invocation inv) {
Controller c=inv.getController();
try {
// 設置Request中漢字的編碼,該方法只對post請求有效,對get請求無效;
// 對於get請求,應該在server.xml中指定:URIEncoding=utf-8;
c.getRequest().setCharacterEncoding("utf-8");
c.getResponse().setCharacterEncoding("utf-8");
inv.invoke();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、servlet ---- response.setCharacter和request.setCharacterEncoding詳解
1、request.setCharacterEncoding():用來確保發往服務器的參數以漢字的編碼來提取,設置從request中取得的值或從數據庫中取出的值。
指定后可以通過request.getParameter()獲取自己想要的字符串,如果沒有提前指定,則會按照服務器端默認的“iso-8859-1”來進行編碼;該方法只對post請求有效,對get請求無效;對於get請求,應該在server.xml中指定:URIEncoding=utf-8;
注意:在執行request.setCharacterEncoding()之前不能執行request.getParameter()方法;
原因:應該是在執行第一個getParameter()的時候,java將會按照編碼分析所有的提交內容,而后續的getParameter()不再進行分析,所以setCharacterEncoding()無效。而對於GET方法提交表單是,提交的內容在URL中,一開始就已經按照編碼分析提交內容,setCharacterEncoding()自然就無效。
2、response.setCharacterEncoding():設置HTTP 響應的編碼,用於設置服務器給客戶端的數據的編碼
一般不會用這個方法來設置響應編碼,
一般使用response.setContentType()方法來設置HTTP 響應的編碼,同時指定了瀏覽器顯示的編碼;
因為他在執行該方法通知服務器端以指定編碼進行編碼后,會自動調用response.setCharacterEncoding()方法來通知瀏覽器以指定編碼來解碼;使用此方法要在response.getWriter()執行之前或response提交之前;
四、如果確實是要處理get請求
可在參數獲取時作轉碼處理
String string = request.getParamers("");
String = new String(string.getBytes("ISO8859-1","utf-8"));
提示:如果已經在tomcat的 server.xml中設置了,可以不對servlet再作配置,但為了穩妥起見(避免忘記配置tomcat),最好也在代碼中對servlet作下設置。