java中的中文亂碼問題應該是我們經常碰到的一個問題,今天就來總結下對於亂碼問題的解決方案:
1. 超連結中帶有的中文字元,<a class="add" href = "system/showDataAdd.action?title=客戶層級&dataType=clientRank&rel=clientRankSet">添加</a>
這樣如果不進行處理在後台得到的資料就會出現中文亂碼的問題,由於超連結實際是用get方式進行傳值的,這個問題的解決方案有:a. 在我們用的Tomcat的conf檔案夾
中找到server.xml,在該檔案中找到<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />,然後在這裡面加
寫URIEncoding="gb2312"即可解決。
2.在服務端用代碼進行處理:例如title是要進行處理的中文字元:
public void setTitle(String title) { try { this.title = new String(title.getBytes("ISO-8859-1"), "gbk"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
3. 頁面端發出的資料做一次encodeURI,伺服器端使用 new String(old.getBytes("iso8859-1"),"utf-8")
如:var url= "AJAXServer?name="+encodeURI($("#userName").val() ) ; // encodeURI處理中文亂碼問題
4. 頁面端發出的資料做兩次encodeURI處理, 伺服器端用URLDecoder.decode(old,"utf-8");
如:var url= "Users?name="+encodeURI(encodeURI($("#username").val() ))+"&password="+encodeURI(encodeURI($("#userpassword").val() ) )+"&type="+encodeURI(encodeURI(input[i].value) ); // encodeURI處理中文亂碼問題