標籤:
一、國際化
準備資源檔,資源檔的命名格式如下:baseName_language_country.propertiesbaseName_language.propertiesbaseName.properties其中baseName是資源檔的基本名,我們可以自訂,但language和country必須是java支援的語言和國家。如:中國大陸: baseName_zh_CN.properties美國: baseName_en_US.properties 現在為應用添加兩個資源檔:第一個存放中文:itcast_zh_CN.properties內容為:welcome=歡迎來到傳智播客第二個存放英語(美國): itcast_en_US.properties內容為: welcome=welcome to itcast 對於中文的屬性檔案,我們編寫好後,應該使用jdk提供的native2ascii命令把檔案轉換為unicode編碼的檔案。命令的使用方式如下:native2ascii 源檔案.properties 目標檔案.properties 配置全域資源與輸出國際化資訊當準備好資源檔之後,我們可以在struts.xml中通過struts.custom.i18n.resources常量把資源檔定義為全域資源檔,如下
<constant name="struts.custom.i18n.resources" value="itcast" />
itcast為資源檔的基本名。 後面我們就可以在頁面或在action中訪問國際化資訊: l在JSP頁面中使用<s:text name=“”/>標籤輸出國際化資訊:<s:text name=“user”/>,name為資源檔中的keyl在Action類中,可以繼承ActionSupport,使用getText()方法得到國際化資訊,該方法的第一個參數用於指定資源檔中的key。l在表單標籤中,通過key屬性指定資源檔中的key,如:<s:textfield name="realname" key="user"/>
package com.dzq.action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class ManagerAction extends ActionSupport{@Overridepublic String execute() throws Exception { ActionContext.getContext().put("message", this.getText("welcome")); return "message";}}
國際化—輸出帶預留位置的國際化資訊資源檔中的內容如下:welcome= {0},歡迎來到傳智播客{1} 在jsp頁面中輸出帶預留位置的國際化資訊
<s:text name="welcome"> <s:param><s:property value="realname"/></s:param> <s:param>學習</s:param></s:text>
在Action類中擷取帶預留位置的國際化資訊,可以使用getText(String key, String[] args)或getText(String aTextName, List args)方法。
package com.dzq.action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class ManagerAction extends ActionSupport{@Overridepublic String execute() throws Exception { ActionContext.getContext().put("message", this.getText("welcome",new String[]{"liming","study"})); return "message";}}
國際化—包範圍資源檔在一個大型應用中,整個應用有大量的內容需要實現國際化,如果我們把國際化的內容都放置在全域資源屬性檔案中,顯然會導致資源檔變的過於龐大、臃腫,不便於維護,這個時候我們可以針對不同模組,使用包範圍來組織國際化檔案。 方法如下: 在java的包下放置package_language_country.properties資源檔,package為固定寫法,處於該包及子包下的action都可以訪問該資源。當尋找指定key的訊息時,系統會先從package資源檔尋找,當找不到對應的key時,才會從常量struts.custom.i18n.resources指定的資源檔中尋找。 國際化—Action範圍資源檔我們也可以為某個action單獨指定資源檔,方法如下:在Action類所在的路徑,放置ActionClassName_language_country.properties資源檔,ActionClassName為action類的簡單名稱。 當尋找指定key的訊息時,系統會先從ActionClassName_language_country.properties資源檔尋找,如果沒有找到對應的key,然後沿著當前包往上尋找基本名為package 的資源檔,一直找到最頂層包。如果還沒有找到對應的key,最後會從常量struts.custom.i18n.resources指定的資源檔中尋找。 國際化—JSP中直接存取某個資源檔struts2為我們提供了<s:i18n>標籤,使用<s:i18n>標籤我們可以在類路徑下直接從某個資源檔中擷取國際化資料,而無需任何配置:
<s:i18n name="itcast"> <s:text name=“welcome”/></s:i18n>
Itcast為類路徑下資源檔的基本名。如果要訪問的資源檔在類路徑的某個包下,可以這樣訪問
<s:i18n name=“cn/itcast/action/package"> <s:text name="welcome"> <s:param>小張</s:param> </s:text></s:i18n>
上面訪問cn.itcast.action包下基本名為package的資源檔
20160502-struts2入門--國際化