也許你已經(jīng)看到了,上述代碼只有文字內(nèi)容不相同,除此之外完全相同。也許你已經(jīng)猜到了,現(xiàn)實(shí)的代碼絕對(duì)不是這樣的。那么是怎么處理的呢?
Internationalization and localization are means of adapting
products such as publications, hardware or software for non-native
environments, especially other nations and cultures.
國(guó)際化(internationalization i18n)和本地化(localization l10n)指讓產(chǎn)品(出版物,軟件,硬件等)能夠適應(yīng)非本地環(huán)境,特別是其他的語(yǔ)言和文化。
針對(duì)計(jì)算機(jī)來說就是讓一個(gè)既可以在中文環(huán)境下運(yùn)行也可以在英語(yǔ),甚至是日語(yǔ)的環(huán)境下運(yùn)行。
特定的方式:有些時(shí)候有些環(huán)境不支持某些語(yǔ)言,例如通常英文環(huán)境不支持中文,所以要將中文改變?yōu)橛⑽目梢宰R(shí)別的形式,在使用的時(shí)候在轉(zhuǎn)變回來。
特殊的方式使用替換ascii的方式,java中提供了一個(gè)native2ascii.exe的工具(在JAVA_HOME\bin目錄下),這個(gè)工具專門用來把某種特定的文字內(nèi)容轉(zhuǎn)變?yōu)樘厥獾母袷健?/div>
例如Message_zh_CN.properties中的內(nèi)容為:
Msg1 = 歡迎
Msg2 = 歡迎到這里!
經(jīng)過命令native2ascii Message_zh_CN.properties之后輸出:
Msg1 = \u6b22\u8fce
Msg2 = \u6b22\u8fce\u5230\u8fd9\u91cc\uff01
這里\u6b22等的數(shù)字是對(duì)應(yīng)漢字(或者其他非英語(yǔ)字符)的unicode表示
第二步,通過當(dāng)前的運(yùn)行環(huán)境確定使用的文件的名字
例如存在上述的三個(gè)文件:
中文中國(guó) Message_zh_CN.properties
日文日本 Message_ja_JP.properties
英文美國(guó) Message_en_US.properties
可以使用java.util.ResouceBundle 類來取得當(dāng)前的資源文件,代碼為:
ResourceBundle rb = ResourceBundle.getBundle("Message");
也可以指語(yǔ)言與國(guó)家特征來獲得想要的文件的內(nèi)容,例如:
ResourceBundle rb = ResourceBundle.getBundle("Message", Locale.JAPAN);
Struts2中如何實(shí)現(xiàn)國(guó)際化(僅限語(yǔ)言層面)
Struts2中使用國(guó)際化的幾個(gè)方法:
1) UI標(biāo)簽
例如:
<s:i18n name="struts.action.test.i18n.Shop">
<s:text name="main.title"/>
</s:i18n>
從指定資源文件struts.action.test.i18n.Shop中找到main.title對(duì)應(yīng)的消息內(nèi)容。
<!-- Second Example -->
<s:text name="main.title" />
從對(duì)應(yīng)的文件中找到main.title對(duì)應(yīng)的消息內(nèi)容。
<!-- Third Examlpe -->
<s:text name="i18n.label.greetings">
<s:param >Mr Smith</s:param>
</s:text>
從對(duì)應(yīng)的文件中找到i18n.label.greetings對(duì)應(yīng)的消息內(nèi)容,其中的{0}參數(shù)將會(huì)被Mr Smith替換。
2) ActionSupport的getText方法
例如:<s:text name="%{getText("i18n.label.greetings")}">
或者在Action中直接使用。
在沒有指定資源文件的情況下,資源文件的查找按如下的順序:
1)ActionClass.properties
2)BaseClass.properties
3)Interface.properties
4)ModelDriven’s Model
5)package.properties
6)search up the i18n message key hierarchy itself
7)global resource properties
例如有如下結(jié)構(gòu):
com/
acme/
package.properties
actions/
package.properties
FooAction.java
FooAction.properties
如果FooAction.properties文件不存在,將使用com/acme/action
/package.properties,如果com/acme/action/package.properties文件不存在,將使用com
/acme/ package.properties,如果還不存在,將使用com/ package.properties等等。
可以通過getText方法,text標(biāo)簽或者i18n標(biāo)簽來訪問資源文件。
可以在struts.properties中通過struts.custom.i18n.resources來指定global的資源綁定。
相關(guān)參考I18n Intercepter
關(guān)于類型轉(zhuǎn)換的國(guó)際化支持參看【第七章 Type Convertion】部分
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程