總結一下,中文亂碼,首先要區分是頁面亂碼、action亂碼,還是資料庫亂碼。大致的原理是java使用unicode編碼-- >window使用gbk(gb2312的擴充集)--mysql預設使用utf-8(unicode的一種編碼方法),這樣轉來轉去就亂碼了 ^_^。解決方案如下:
1. 在struts2裡面,最好將所有字元都設成utf-8。
<%@ page contentType="text/html; charset=UTF-8"%> <%@ page pageEncoding="UTF-8" %> |
1.1 在jsp頁面設定字元編碼。這邊有必有說明的是如果是jsp+java bean+servlet的方案,中文亂碼很好解決,統一設成gb2312就可以了。
1.2 使用struts架構字元集不能設成gb2312,要改成utf-8。 2. 在struts.properties 添加:
struts.devMode=false struts.enable.DynamicMethodInvocation=true struts.i18n.reload=true struts.ui.theme=simple struts.locale=zh_CN struts.i18n.encoding=UTF-8 struts.serve.static.browserCache=false struts.url.includeParams=none |
其中locale、encoding就是字元集的設定了。
3. 在web.xml加個filter
<!-- zh-cn encoding --> <filter> <filter-name>struts-cleanup</filter-name> <filter-class> org.apache.struts2.dispatcher.ActionContextCleanUp </filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
跟上述方法,類似還有在action中設定字元編符.
HttpServletResponse response = null; response = ServletActionContext.getResponse(); request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8");
|
通過上述方法,基本就可以搞定中文亂碼的問題了。當然,也有例外(如web server的版本/資料庫的版本等等)。象在我的一個項目碰到一個中文亂碼,tomcate5.5是會亂碼的,而在tomcate6中就不會。這邊就涉及到tomcate connector字元的設定了。
<Connector port="80" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="GBK" /> |
--------------------------------------------------------------------
後記之一:在使用struts2時,仍是遇到一種亂碼。後來調試才發現,struts2的web.xml配置是有順序的。
在web.xml中EncodingFilter的位置應該在Struts2的FilterDispatcher之前,因為要先調整字元集,然後進入Action。
按照Struts2的API,filter的順序是
struts-cleanup filter
SiteMesh filter
FilterDispatcher
--------------------------------------------------------------------
後記之二:這個方法是下下策了,只有在前面的方法都無效時才使用。
在action中直接使用request.getParameter()時;還是出現亂碼。原因分析如下:
1、getParameter()是有帶字元參數的。例:
String s = (String)request.getParameter("txt").getBytes("iso-8859-1");
2、String也可以帶有字元參數。
String(byte[] bytes, String charsetName)
構造一個新的 String,方法是使用指定的字元集解碼指定的位元組數組。
例:String s = new String("中文","utf-8");
3、綜合上述兩點,編寫一個類來完成此項任務
public class ConvertCharacter{ public String Convert(String s){ String result; byte[] temp ; try{ temp = s.getBytes("iso-8859-1"); result = new String(temp,"utf-8"); } return result; } } |