Struts 2 仍有多語言的支援,相關的文件可以查看 http://struts.apache.org/release/2.2.x/docs/localization.html ,搜尋的順序是:

  1. ActionClass.properties
  2. Interface.properties (every interface and sub-interface)
  3. BaseClass.properties (all the way to Object.properties)
  4. ModelDriven's model (if implements ModelDriven), for the model object repeat from 1
  5. package.properties (of the directory where class is located and every parent directory all the way to the root directory)
  6. search up the i18n message key hierarchy itself
  7. global resource properties

參考網文 Struts 2 – Resource bundle example 的一張圖可以大致瞭解其搜尋順序

 若 struts.xml 檔內容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
    <constant name="struts.devMode" value="true"/>
    <constant name="struts.custom.i18n.resources" value="messages" />  

    <package name="default" namespace="/" extends="struts-default">

        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>
      
        <action name="Login_*" method="{1}" class="com.gu.Login">
            <result name="input">/Login.jsp</result>
        </action>
    </package>
</struts>

而 properties 檔:global.properties & package.properties 擺放的位置如下圖:

struts_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/

 

arrow
arrow
    文章標籤
    struts2 Localization properties
    全站熱搜

    MIS 發表在 痞客邦 留言(0) 人氣()