<%@ page contentType="text/html; charset=UTF-8"%> <%@ page pageEncoding="UTF-8" %> |
struts.devMode=false struts.locale=zh_CN struts.serve.static.browserCache=false |
其中l(wèi)ocale、encoding就是字符集的設(shè)定了。
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中設(shè)定字符編符.
|
通過上述方法,基本就可以搞定中文亂碼的問題了。當(dāng)然,也有例外(如web server的版本\數(shù)據(jù)庫的版本等等)。象在我的一個項(xiàng)目碰到一個中文亂碼,tomcate5.5是會亂碼的,而在tomcate6中就不會。這邊就涉及到tomcate connector字符的設(shè)置了。
<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í),仍是遇到一種亂碼。后來調(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
--------------------------------------------------------------------
后記之二:這個方法是下下策了,只有在前面的方法都無效時(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)造一個新的 String,方法是使用指定的字符集解碼指定的字節(jié)數(shù)組。
例:String s = new String("中文","utf-8");
3、綜合上述兩點(diǎn),編寫一個類來完成此項(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; } } |