Tomcat 改伺服器編碼(Java 修改字串編碼格式)

劍握在手發表於2013-11-30

對於客戶端發來的漢字,我們一般需要轉碼:

------------------------------------------------------------------------------------

request.setCharacterEncoding("UTF-8");//這樣設定客戶機發來資料文字格式只對post方式有效

String line = request.getParameter("username");  

System.out.println(line);

-------------------------------------------------------------

String line = request.getParameter("username");

line=(new String(line.getBytes("iso8859-1"),"UTF-8"));//對於get方式,只能這樣了。

-------------------------------------------------------------------------------------

有沒有辦法不用這麼麻煩?有,配置Tomcat伺服器的server.xml 中的connector

先看一下API:http://localhost:8080/docs/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.

 

意思是如果不配置這個URIEncoding 那麼採用預設的ISO-8859-1

     <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>

這樣配置即可。

 

 

 

還有一個方法:

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.

 

     <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" useBodyEncodingForURI="true"/>

這樣一改,那麼:

request.setCharacterEncoding("UTF-8");//這樣設定客戶機發來資料文字格式就不只對post方式有效了,對get方式也有效。

 

 

Tomcat 的log亂碼解決方式:

catalina.bat 中找到這一句

set LOGGING_CONFIG=-Djava.util.logging.config.file="%CATALINA_BASE%\conf\logging.properties"      在後邊加上:-Dfile.encoding="UTF-8" 

相關文章