Struts 2 仍有多語言的支援,相關的文件可以查看 http://struts.apache.org/release/2.2.x/docs/localization.html ,搜尋的順序是:
- ActionClass.properties
- Interface.properties (every interface and sub-interface)
- BaseClass.properties (all the way to Object.properties)
- ModelDriven's model (if implements ModelDriven), for the model object repeat from 1
- package.properties (of the directory where class is located and every parent directory all the way to the root directory)
- search up the i18n message key hierarchy itself
- global resource properties
參考網文 Struts 2 – Resource bundle example 的一張圖可以大致瞭解其搜尋順序
若 struts.xml 檔內容如下
<?xml version="1.0" encoding="UTF-8" ?> |
而 properties 檔:global.properties & package.properties 擺放的位置如下圖:
所以在 com.gu 裡的 package.properties 內的值就會優先於 global.properties。而 global-resource 的設定可以參考: http://struts.apache.org/release/2.3.x/docs/how-do-i-set-a-global-resource-bundle.html。但個人覺得最好用的是在 struts.xml 中設定 <constant name="struts.custom.i18n.resources" value="messages" />,然後在message.properties 檔作維護就好。
取得的方法有下列幾個方法:
1. Action class:使用函數 getText("key")
public class Login extends ActionSupport{ ... public void validate(){ if("".equals(getUsername())){ addFieldError("username", getText("username.required")); } } } |
2. property tag: property (屬性)的 tag 用 getText("key") 來取值
<s:property value="getText('username')" />
|
3. text tag:text(文字) 的 tag 用 "name" 的屬性來取值
<s:text name="username" />
|
4. Key attribute:以 "key" 的屬性來取值
<s:textfield key="username" />
|
5. I18n tag :指定檔案取值,例如讀取檔案 com.gu.ebs.package.properties
<s:i18n name="com.gu.ebs.package" > <s:text name="username" /> </s:i18n> |
參考:
http://struts.apache.org/release/2.2.x/docs/localization.html
http://www.mkyong.com/struts2/struts-2-resource-bundle-example/
http://www.mkyong.com/struts2/struts-2-key-attribute-example/