struts2中文亂碼解決方法:
http://blog.sina.com.cn/s/blog_4b652239010008za.html
總結(jié)一下,中文亂碼,首先要區(qū)分是頁(yè)面亂碼、action亂碼,還是數(shù)據(jù)庫(kù)亂碼。大致的原理是java使用unicode編碼-->window使用gbk(gb2312的擴(kuò)展集)--mysql默認(rèn)使用utf-8(unicode的一種編碼方法),這樣轉(zhuǎn)來(lái)轉(zhuǎn)去就亂碼了^_^。解決方法如下:
1. 在struts2里面,最好將所有字符都設(shè)成utf-8。
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="UTF-8" %>
1.1 在jsp頁(yè)面設(shè)定字符編碼。這邊有必有說(shuō)明的是如果是jsp+java bean+servlet的方案,中文亂碼很好解決,統(tǒng)一設(shè)成gb2312就可以了。
1.2 使用struts框架字符集不能設(shè)成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
其中l(wèi)ocale、encoding就是字符集的設(shè)定了。
3. 在web.xml加個(gè)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中設(shè)定字符編符.
HttpServletResponse response = null;
response = ServletActionContext.getResponse();
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
<Connector port="80" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="GBK" />
--------------------------------------------------------------------
后記之一:在使用struts2時(shí),仍是遇到一種亂碼。后來(lái)調(diào)試才發(fā)現(xiàn),struts2的web.xml配置是有順序的。
在web.xml中EncodingFilter的位置應(yīng)該在Struts2的FilterDispatcher之前,因?yàn)橐日{(diào)整字符集,然后進(jìn)入Action。
按照Struts2的API,filter的順序是
struts-cleanup filter
SiteMesh filter
FilterDispatcher
--------------------------------------------------------------------
后記之二:這個(gè)方法是下下策了,只有在前面的方法都無(wú)效時(shí)才使用。
在action中直接使用request.getParameter()時(shí);還是出現(xiàn)亂碼。原因分析如下:
1、getParameter()是有帶字符參數(shù)的。例:
String s = (String)request.getParameter("txt").getBytes("iso-8859-1");
2、String也可以帶有字符參數(shù)。
String(byte[] bytes, String charsetName)
構(gòu)造一個(gè)新的 String,方法是使用指定的字符集解碼指定的字節(jié)數(shù)組。
例:String s = new String("中文","utf-8");
3、綜合上述兩點(diǎn),編寫一個(gè)類來(lái)完成此項(xiàng)任務(wù)
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;
}
}
通過(guò)上述方法,基本就可以搞定中文亂碼的問(wèn)題了。當(dāng)然,也有例外(如web server的版本\數(shù)據(jù)庫(kù)的版本等等)。象在我的一個(gè)項(xiàng)目碰到一個(gè)中文亂碼,tomcate5.5是會(huì)亂碼的,而在tomcate6中就不會(huì)。這邊就涉及到tomcate connector字符的設(shè)置了。