struts2學習筆記之十八(國際化),struts2學習筆記
java國際化
程式國際化:
程式可以根據機器所在國家、語言環境,自動翻譯內容
國際化的本質就是:尋找、替換,從資源套件裡找到相應國家下的關鍵字對應的語言文字
國際化的步驟:
(1)提供國際化資源檔
如果國家化資源套件中有非西歐字元,需要使用native2ascii處理檔案,
native2ascii sourcefile destfile
產生一個是Unicode字元的檔案
資源檔的寫法:檔案名稱語言代碼國家代碼
xiyang_en_US.properties
hi=”hello”
xiyang_zh_CN.properties
hi=”你好”
注意:不能直接寫”你好”,要使用Unicode編碼,轉換之後hi=”\u4f60\u597d”
(2)在程式中輸出的是國際化訊息的key值,這樣程式就會從資源套件中搜尋key的value
-
提供國際化資源檔
mess_zh_CN.properties
-
java國際化
public class LocaleTest{ public static class main(String[] args){ //查看系統支援的語言和國家代碼 System.out.println("查看語言、國家代碼"); Locale[] locales = Locale.getAvailableLocales(); for(Locale locale: locales){ System.out.println(locale.getDisaplayLanguage() +"---->"+locale.getLanguage()); System.out.println(locale.getDispalayCountry() +"---->"+locale.getCountry()) } //已經提供了兩個資源套件hi_en_US.properties,hi_zh_CN.properties //擷取原生環境 Locale locale = Locale.getDefault(Locale.Ctegory.FORMAT); //綁定資源檔 ResouceBundle bundle=ResourceBundle.getBundle("hi",locale); System.out.println(bundle.getString("hi")); }}
struts2的國際化執行個體JSP國際化
<!--JSP頁面的國際化--><!--name表示國際化訊息的baseName--><!--注意s:i18n的作用範圍--><%@ page language="java" import="java.util.*" pageEncoding="gb2312"%><%@ taglib prefix="s" uri="/struts-tags"%><!-- 最好設定一個resource檔案夾,且放在src下面 ,放在content檔案下會出錯--><!--重點--><s:i18n name="resource/I18nJSP" ><html> <head> <title> <s:text name="LoginPage"/> </title> </head> <body> <!-- 下面的表單的好處 1、更簡單 2、自動支援2列布局 3、自動輸出類型轉換失敗,輸入校正失敗的錯誤資訊 --> <s:form action="loginAction"> <s:textfield name="name" key="username" /> <s:textfield name="pass" key="password" /> <s:submit key="login"/> </s:form> </body></html></s:i18n><!--檔案內容:I18nJSP_zh_CN.propertiesLoginPage=\u767B\u9646username=\u7528\u6237\u540Dpassword=\u5BC6\u7801login=\u767B\u9646I18nJSP_en_US.propertiesLoginPage=Login Pageusername=usernamepassword=passwordlogin=login in-->
Action類國際化
public String execute() throws Exception { // TODO Auto-generated method stub if(name.equals("me") && pass.equals("12345")){ setTip(getText("login", new String[]{name})); return SUCCESS; } return ERROR; }/*與action同名,且放在同一個包下面,系統會自動載入Login_zh_CN.propertieslogin=\u5F88\u9AD8\u5174\u89C1\u5230\u4F60\uFF0C{0}\uFF01Login_en_US.propertieslogin=Nice to meet you,{0}\!*/
全域國際化
將所有的國際化的key集中到一個檔案中,然後直接由系統自動調用
重點是struts.xml中配置常量struts.custom.i18n.resoures
struts 預設使用瀏覽器設定選擇國家和語言
提供機制讓使用者選擇國家語言環境
A、根據request_locale來確定確定
如在提交請求時加上request_locale=en_US來設定語言環境為English
B、直接通過瀏覽器選項修改語言環境
重點就是在struts.xml中添加常量:<constant name="struts.custom.i18n.resources" value="/resource/globalI18n"></constant>
總結:
jsp頁面和全域國際化都是需要指定資源檔所在的位置
<s:i18n name="">
<constant name="struts.custom.i18n.resources" value="/resource/globalI18n"></constant>
action和package範圍的國際化會自動載入
只需要在命名的時候注意,action範圍需要與action同名,package需要命名為package_xx_xx.properties