終於在自己的項目中引入struts2了,但一上來就來一個中文亂碼的問題。google了半天找了幾個不痛不癢的結果,很是不滿意。又調試了半天,終於 解決了中文亂碼的問題。總結一下,中文亂碼,首先要區分是頁面亂碼、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=falsestruts.enable.DynamicMethodInvocation=truestruts.i18n.reload=truestruts.ui.theme=simple

struts.locale=zh_CNstruts.i18n.encoding=UTF-8

struts.serve.static.browserCache=falsestruts.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 filterSiteMesh filterFilterDispatcher

--------------------------------------------------------------------

後記之二:這個方法是下下策了,只有在前面的方法都無效時才使用。

在action中直接使用request.getParameter()時;還是出現亂碼。原因分析如下:

1、getParameter()是有帶字元參數的。例:

String s = (String)request.getParameter("txt").getBytes("iso-8859-1");

2、String也可以帶有字元參數。

String(byte[]bytes, StringcharsetName)構造一個新的 String,方法是使用指定的字符集解碼指定的位元組數組。

例:String s = new String("中文","utf-8");

3、綜合上述兩點,編寫一個類來完成此項任務

public class ConvertCharacter{

public String Convert(String s){

Stringresult;

byte[] temp ;

try{

temp = s.getBytes("iso-8859-1");

result = new String(temp,"utf-8");

}

return result;

}

}

推薦閱讀:

查看原文 >>
相关文章