Java中文問題一直困擾著很多初學(xué)者,如果了解了Java系統(tǒng)的中文問題原理,我們就可以對中文問題能夠采取根本的解決之道。
最古老的解決方案是使用String的字節(jié)碼轉(zhuǎn)換,這種方案問題是不方便,我們需要破壞對象封裝性,進行字節(jié)碼轉(zhuǎn)換。
還有一種方式是對J2EE容器進行編碼設(shè)置,如果J2EE應(yīng)用系統(tǒng)脫離該容器,則會發(fā)生亂碼,而且指定容器配置不符合J2EE應(yīng)用和容器分離的原則。
在Java內(nèi)部運算中,涉及到的所有字符串都會被轉(zhuǎn)化為UTF-8編碼來進行運算。那么,在被Java轉(zhuǎn)化之前,字符串是什么樣的字符集? Java總是根據(jù)操作系統(tǒng)的默認編碼字符集來決定字符串的初始編碼,而且Java系統(tǒng)的輸入和輸出的都是采取操作系統(tǒng)的默認編碼。
因此,如果能統(tǒng)一Java系統(tǒng)的輸入、輸出和操作系統(tǒng)3者的編碼字符集合,將能夠使Java系統(tǒng)正確處理和顯示漢字。這是處理Java系統(tǒng)漢字的一個原則,但是在實際項目中,能夠正確抓住和控制住Java系統(tǒng)的輸入和輸出部分是比較難的。J2EE中,由于涉及到外部瀏覽器和數(shù)據(jù)庫等,所以中文問題亂碼顯得非常突出。
J2EE應(yīng)用程序是運行在J2EE容器中。在這個系統(tǒng)中,輸入途徑有很多種:一種是通過頁面表單打包成請求(request)發(fā)往服務(wù)器的;第二種是通過數(shù)據(jù)庫讀入;還有第3種輸入比較復(fù)雜,JSP在第一次運行時總是被編譯成Servlet,JSP中常常包含中文字符,那么編譯使用javac時,Java將根據(jù)默認的操作系統(tǒng)編碼作為初始編碼。除非特別指定,如在Jbuilder/eclipse中可以指定默認的字符集。
輸出途徑也有幾種:第一種是JSP頁面的輸出。由于JSP頁面已經(jīng)被編譯成Servlet,那么在輸出時,也將根據(jù)操作系統(tǒng)的默認編碼來選擇輸出編碼,除非指定輸出編碼方式;還有輸出途徑是數(shù)據(jù)庫,將字符串輸出到數(shù)據(jù)庫。
由此看來,一個J2EE系統(tǒng)的輸入輸出是非常復(fù)雜,而且是動態(tài)變化的,而Java是跨平臺運行的,在實際編譯和運行中,都可能涉及到不同的操作系統(tǒng),如果任由Java自由根據(jù)操作系統(tǒng)來決定輸入輸出的編碼字符集,這將不可控制地出現(xiàn)亂碼。
正是由于Java的跨平臺特性,使得字符集問題必須由具體系統(tǒng)來統(tǒng)一解決,所以在一個Java應(yīng)用系統(tǒng)中,解決中文亂碼的根本辦法是明確指定整個應(yīng)用系統(tǒng)統(tǒng)一字符集。
指定統(tǒng)一字符集時,到底是指定ISO8859_1 、GBK還是UTF-8呢?
(1)如統(tǒng)一指定為ISO8859_1,因為目前大多數(shù)軟件都是西方人編制的,他們默認的字符集就是ISO8859_1,包括操作系統(tǒng)Linux和數(shù)據(jù)庫MySQL等。這樣,如果指定Jive統(tǒng)一編碼為ISO8859_1,那么就有下面3個環(huán)節(jié)必須把握:
開發(fā)和編譯代碼時指定字符集為ISO8859_1。
運行操作系統(tǒng)的默認編碼必須是ISO8859_1,如Linux。
在JSP頭部聲明:<%@ page contentType="text/html;charset=ISO8859_1" %>。
(2)如果統(tǒng)一指定為GBK中文字符集,上述3個環(huán)節(jié)同樣需要做到,不同的是只能運行在默認編碼為GBK的操作系統(tǒng),如中文Windows。
統(tǒng)一編碼為ISO8859_1和GBK雖然帶來編制代碼的方便,但是各自只能在相應(yīng)的操作系統(tǒng)上運行。但是也破壞了Java跨平臺運行的優(yōu)越性,只在一定范圍內(nèi)行得通。例如,為了使得GBK編碼在linux上運行,設(shè)置Linux編碼為GBK。
那么有沒有一種除了應(yīng)用系統(tǒng)以外不需要進行任何附加設(shè)置的中文編碼根本解決方案呢?
將Java/J2EE系統(tǒng)的統(tǒng)一編碼定義為UTF-8。UTF-8編碼是一種兼容所有語言的編碼方式,惟一比較麻煩的就是要找到應(yīng)用系統(tǒng)的所有出入口,然后使用UTF-8去“結(jié)扎”它。
一個J2EE應(yīng)用系統(tǒng)需要做下列幾步工作:
- 開發(fā)和編譯代碼時指定字符集為UTF-8。JBuilder和Eclipse都可以在項目屬性中設(shè)置。
- 使用過濾器,如果所有請求都經(jīng)過一個Servlet控制分配器,那么使用Servlet的filter執(zhí)行語句,將所有來自瀏覽器的請求(request)轉(zhuǎn)換為UTF-8,因為瀏覽器發(fā)過來的請求包根據(jù)瀏覽器所在的操作系統(tǒng)編碼,可能是各種形式編碼。關(guān)鍵一句:
request.setCharacterEncoding("UTF-8")。
網(wǎng)上有此filter的源碼,Jdon框架源碼中com.jdon.util.SetCharacterEncodingFilter
需要配置web.xml 激活該Filter。
- 在JSP頭部聲明:<%@ page contentType="text/html;charset= UTF-8" %>。
- 在Jsp的html代碼中,聲明UTF-8:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- 設(shè)定數(shù)據(jù)庫連接方式是UTF-8。例如連接MYSQL時配置URL如下:
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
一般數(shù)據(jù)庫都可以通過管理設(shè)置設(shè)定UTF-8
- 其他和外界交互時能夠設(shè)定編碼時就設(shè)定UTF-8,例如讀取文件,操作XML等。
以上討論了Java/J2EE的中文問題。如果整個應(yīng)用系統(tǒng)是從開始進行開發(fā),那么統(tǒng)一指定編碼為UTF-8就非常容易做到。如果是在英文源代碼基礎(chǔ)上二次開發(fā),那么首先要將原來的源代碼轉(zhuǎn)換為統(tǒng)一編碼UTF-8,那么這種轉(zhuǎn)換工作會帶來一定的麻煩。
有了這個解決方案,無論使用什么框架Struts 或JSF或未來出現(xiàn)的Java技術(shù),統(tǒng)一成UTF-8的方案都不會出現(xiàn)亂碼,筆者以前在Jsp/Servlet時就基于這個原則,后來使用Struts等框架,從未被亂碼困擾過,希望本方案公布出來供更多初學(xué)者分享,減少Java/J2EE的第一個攔路虎,也避免采取一些臨時解決方案。
***********************************************************************************************************************
? <filter> ?
? <filter-name>encodingFilter</filter-name> ?
? <filter-class> ?
? org.springframework.web.filter.CharacterEncodingFilter ?
? </filter-class> ?
? <init-param> ?
? <param-name>encoding</param-name> ?
? <param-value>UTF-8</param-value> ?
? </init-param> ?
? <init-param> ?
? <param-name>forceEncoding</param-name> ?
? <param-value>true</param-value> ?
? </init-param> ?
? </filter> ?
? ?
? ? ? ? ? ? ? ? ? ? <filter-mapping> ?
? <filter-name>encodingFilter</filter-name> ?
? <servlet-name>action</servlet-name> ?
? </filter-mapping>
***********************************************************************************************
hibernate+mysql寫入數(shù)據(jù)庫的中文是亂碼,怎么解決??
hibernate.hbm.xml加上屬性.
<property name=\"connection.useUnicode\">true</property>
<property name=\"connection.characterEncoding\">UTF-8</property>
mysql 的驅(qū)動用3.0.15以上版本的,
加個Filter, 使用UTF-8字符集就可以了,
?
1.使ApplicationResources.properties支持中文
建立一個ApplicationResources_ISO.properties文件,把應(yīng)用程序用的message都寫進去,然后在dos下執(zhí)行這個命令,
native2ascii?-encoding?gb2312?ApplicationResources_ISO.properties?ApplicationResources.properties
這樣就會將ISO編碼的ApplicationResources轉(zhuǎn)換成GB2312編碼的格式了,同時保存到ApplicationResources.properties.
native2ascii這個工具是jdk自帶的一個東東,所以如果path都設(shè)定正確就可以直接運行了,你可以在$java_home$/bin下找到他。
轉(zhuǎn)換后的中文類似于這個樣子
iso?格式下?:tj.type=商品車類型
gb2312格式下?:tj.type=\u5546\u54c1\u8f66\u7c7b\u578b
然后在struts-config.xml中設(shè)置應(yīng)用這個資源文件
?<message-resources?parameter=\"com.huahang.tj.ApplicationResources\"?key=\"org.apache.struts.action.MESSAGE\"?/>
開發(fā)jsp時在jsp的開頭寫上<%@?page?contentType=\"text/html;?charset=gb2312\"?%>,將字符集設(shè)置成gb2312就可以了。
2.使數(shù)據(jù)庫操作支持中文。
數(shù)據(jù)庫操作支持中文一直讓我比較頭痛,但是感謝善解人衣向我推薦了www.chinaxp.org,這個網(wǎng)站是用struts框架開發(fā)的,而且
開放源碼,下載了源碼后發(fā)現(xiàn)它的中文處理得很好,閱讀部分源碼,沒有發(fā)現(xiàn)什么特殊的字符集轉(zhuǎn)換,很納悶,偶然看到樓上網(wǎng)友
留言知道原來servlet可以統(tǒng)一設(shè)置字符轉(zhuǎn)換。chinaxp.org就是這么做的。
在web.xml中加上
??<filter>
????<filter-name>Set?Character?Encoding</filter-name>
????<filter-class>com.huahang.tj.struts.filters.SetCharacterEncodingFilter</filter-class>
????<init-param>
??????<param-name>encoding</param-name>
??????<param-value>GB2312</param-value>
????</init-param>
????<init-param>
??????<param-name>ignore</param-name>
??????<param-value>true</param-value>
????</init-param>
??</filter>
??<filter-mapping>
????<filter-name>Set?Character?Encoding</filter-name>
????<servlet-name>action</servlet-name>
??</filter-mapping>
這里會涉及一個bean,源碼如下:
/*
?*?XP?Forum
?*????
?*?Copyright?(c)?2002-2003?RedSoft?Group.??All?rights?reserved.
?*
?*/
package?com.huahang.tj.struts.filters;
import?javax.servlet.*;
import?java.io.IOException;
/**
?*?<p>Filter?that?sets?the?character?encoding?to?be?used?in?parsing?the
?*?incoming?request,?either?unconditionally?or?only?if?the?client?did?not
?*?specify?a?character?encoding.??Configuration?of?this?filter?is?based?on
?*?the?following?initialization?parameters:</p>
?*?<ul>
?*?<li><strong>encoding</strong>?-?The?character?encoding?to?be?configured
?*?????for?this?request,?either?conditionally?or?unconditionally?based?on
?*?????the?<code>ignore</code>?initialization?parameter.??This?parameter
?*?????is?required,?so?there?is?no?default.</li>
?*?<li><strong>ignore</strong>?-?If?set?to?\"true\",?any?character?encoding
?*?????specified?by?the?client?is?ignored,?and?the?value?returned?by?the
?*?????<code>selectEncoding()</code>?method?is?set.??If?set?to?\"false,
?*?????<code>selectEncoding()</code>?is?called?<strong>only</strong>?if?the
?*?????client?has?not?already?specified?an?encoding.??By?default,?this
?*?????parameter?is?set?to?\"true\".</li>
?*?</ul>
?*
?*?<p>Although?this?filter?can?be?used?unchanged,?it?is?also?easy?to
?*?subclass?it?and?make?the?<code>selectEncoding()</code>?method?more
?*?intelligent?about?what?encoding?to?choose,?based?on?characteristics?of
?*?the?incoming?request?(such?as?the?values?of?the?<code>Accept-Language</code>
?*?and?<code>User-Agent</code>?headers,?or?a?value?stashed?in?the?current
?*?user\'s?session.</p>
?*
?*?@author?<a?href=\"mailto:jwtronics@yahoo.com\">John?Wong</a>
?*
?*?@version?$Id:?SetCharacterEncodingFilter.java,v?1.1?2002/04/10?13:59:27?johnwong?Exp?$
?*/
public?class?SetCharacterEncodingFilter?implements?Filter?{
????//?-----------------------------------------------------?Instance?Variables
????/**
?????*?The?default?character?encoding?to?set?for?requests?that?pass?through
?????*?this?filter.
?????*/
????protected?String?encoding?=?null;
????/**
?????*?The?filter?configuration?object?we?are?associated?with.??If?this?value
?????*?is?null,?this?filter?instance?is?not?currently?configured.
?????*/
????protected?FilterConfig?filterConfig?=?null;
????/**
?????*?Should?a?character?encoding?specified?by?the?client?be?ignored?
?????*/
????protected?boolean?ignore?=?true;
????//?---------------------------------------------------------?Public?Methods
????/**
?????*?Take?this?filter?out?of?service.
?????*/
????public?void?destroy()?{
????????this.encoding?=?null;
????????this.filterConfig?=?null;
????}
????/**
?????*?Select?and?set?(if?specified)?the?character?encoding?to?be?used?to
?????*?interpret?request?parameters?for?this?request.
?????*
?????*?@param?request?The?servlet?request?we?are?processing
?????*?@param?result?The?servlet?response?we?are?creating
?????*?@param?chain?The?filter?chain?we?are?processing
?????*
?????*?@exception?IOException?if?an?input/output?error?occurs
?????*?@exception?ServletException?if?a?servlet?error?occurs
?????*/
????public?void?doFilter(ServletRequest?request,?ServletResponse?response,
?????????????????????????FilterChain?chain)
????throws?IOException,?ServletException?{
????????//?Conditionally?select?and?set?the?character?encoding?to?be?used
????????if?(ignore?||?(request.getCharacterEncoding()?==?null))?{
????????????String?encoding?=?selectEncoding(request);
????????????if?(encoding?!=?null)
????????????????request.setCharacterEncoding(encoding);
????????}
????//?Pass?control?on?to?the?next?filter
????????chain.doFilter(request,?response);
????}
????/**
?????*?Place?this?filter?into?service.
?????*
?????*?@param?filterConfig?The?filter?configuration?object
?????*/
????public?void?init(FilterConfig?filterConfig)?throws?ServletException?{
????this.filterConfig?=?filterConfig;
????????this.encoding?=?filterConfig.getInitParameter(\"encoding\");
????????String?value?=?filterConfig.getInitParameter(\"ignore\");
????????if?(value?==?null)
????????????this.ignore?=?true;
????????else?if?(value.equalsIgnoreCase(\"true\"))
????????????this.ignore?=?true;
????????else?if?(value.equalsIgnoreCase(\"yes\"))
????????????this.ignore?=?true;
????????else
????????????this.ignore?=?false;
????}
????//?------------------------------------------------------?Protected?Methods
????/**
?????*?Select?an?appropriate?character?encoding?to?be?used,?based?on?the
?????*?characteristics?of?the?current?request?and/or?filter?initialization
?????*?parameters.??If?no?character?encoding?should?be?set,?return
?????*?<code>null</code>.
?????*?<p>
?????*?The?default?implementation?unconditionally?returns?the?value?configured
?????*?by?the?<strong>encoding</strong>?initialization?parameter?for?this
?????*?filter.
?????*
?????*?@param?request?The?servlet?request?we?are?processing
?????*/
????protected?String?selectEncoding(ServletRequest?request)?{
????????return?(this.encoding);
????}
}//EOC
加上這個后,在action中就可以直接從form中接收gb2312編碼的數(shù)據(jù)了,返回時自然也是gb2312了。
但是這個好像需要servlet?2.2以上的容器
綜合上面的方法,我解決了struts中的中文問題,現(xiàn)在還沒發(fā)現(xiàn)新的問題。