首先出現中文亂碼的原因是tomcat默認的編碼方式是"ISO-8859-1",這種編碼方式以單個字節作為一個字符,而漢字是以兩個字節表示一個字符的。
一,get請求參數中文亂碼的解決辦法
對於get請求解決中文亂碼有兩種途徑
一種是修改tomcat默認的編碼方式為"UTF-8"
在tomcat的server.xml里把
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
修改為
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
另一種則是代碼層次解決中文亂碼,該方式需要前端與后台都要做相應編碼
來自頁面的一個get請求:
window.location.href = getContextPath()+"/manage/user/detail?name="+encodeURI(encodeURI("小明"));
服務器端:
String name = request.getParameter("name");
orgname = URLDecoder.decode(name,"UTF-8");
因為get請求的參數在請求行上,我們不能像解決post請求那樣使用 request.setCharacterEncoding("UTF-8");這種方式是修改方法體的編碼方式。
所以只能使用以上的方式分別對請求行的漢字進行編碼和解碼。其實解決get請求中文亂碼問題最好的方式是避免使用中文,若帶有中文參數盡量使用post請求進行傳遞。
二,post請求參數中文亂碼的解決辦法
對於post請求,請求中問亂碼的兩種解決辦法,就喜聞樂見了。一般也不會有post請求參數中文亂碼吧,任何一個java的web項目應該都配置了字符集過濾器。
(1): request.setCharacterEncoding("UTF-8");
(2):
<filter>
<description>字符集過濾器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集編碼</description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
