參考:java
http://blog.csdn.net/error_case/article/details/8250209web
中文亂碼是個老生常談的問題,通常狀況下,只要保證頁面,web服務器,數據庫的編碼一致,不多出現中文亂碼,不過最近項目中碰到了一個之前沒在乎過的問題,就是post提交和get提交的中文亂碼處理方式不同的問題,具體狀況是這樣的:爲了方便,我將tomcat服務器的編碼方式設置爲utf-8,設置方法以下:ajax
在tomcat的server.xml的
<Connector port="8080" protocol="HTTP/1.1"?
connectionTimeout="20000"?
redirectPort="8443"/>
節點中,加上useBodyEncodingForURI="true"這個屬性,這屬性的默認值 是false,另外也能夠在那個節點中加上URIEncoding="UTF-8"屬性。spring
設置後,重啓tomcat,發現get方式提交的數據沒中文亂碼,但post提交的數據依舊存在中文亂碼,經過在網上搜索一看,這樣的設置只能處理get請求方式的中文亂碼,不能處理post請求方式的,緣由應該是get方式是將參數拼接在url中的,而post方式是將參數寫在http協議的body中的;post還亂碼,我在java代碼中轉碼看了下,轉碼後正常,轉碼代碼:數據庫
String a = new String(request.getParameter("a").getBytes("ISO8859_1"),"UTF-8");json
從這能夠看出來,tomcat服務器仍是以默認編碼方式提交了請求,爲了改變請求提交編碼方式,就須要設置request.setCharacterEncoding("UTF-8");,設置後測試,沒中文亂碼了,不過若是在開發中每一個jsp頁面這樣寫的話,也不太和諧,爲了方便,能夠製做一個filter,在處理請求前,對全部的request都設置它的編碼爲須要的編碼方式,這樣就不用在每次處理的時候來設置編碼了。tomcat
-----------------------------------服務器
hl add 20140107 不少框架都提供了相似的filter ,好比spirngmvcmvc
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>app
---------------------
hl add 20140108 ajax, json經過post方式走filter沒問題,可是若是經過get方式會出現亂碼
解決方案:jsp頁面拼裝的時候經過encodeURI轉碼,java接收的時候也經過URLDecoder.decode轉碼
js:
var age = encodeURI($(「age」).attr(「value));
var userName = encodeURI($(「userName」).attr(「value));
var user = {userName: userName, age: age};
$.ajax({
type: 「get」,
data: user
})
java:
String userName = URIDecoder.decode(user.userName);
-----------------------------------------------------------------------------------------
測試結果:
增長URIEncoding="UTF-8"屬性不行,修改爲URIEncoding="GBK"就能夠了,不知何故。