【Struts2系列】Struts2 國際化資源文件的機制原理

【Struts2國際化資源文件定義的3種範圍方法】

 1)全局的國際化資源文件,對所有的Action和View都有效

    定義方式:

        在struts.xml中增加全局資源文件定路徑定義:
        <constant name="struts.custom.i18n.resources" value="globalMessage"></constant>

        對應的資源文件爲classpath根目錄位置:

        globalMessage.properties,

        globalMessage_en.properties,

        globalMessage_cn_ZH.properties

  2)包範圍的國際化資源文件,對package目錄下的Action和View有效

       不需要額外的配置,只需要將資源文件定義爲 :

         package.properties,

        package_en.properties,

        package_cn_ZH.properties,

       並放在對應classpath所在的package目錄下      

  3)Action範圍的國際化資源文件,只對某個Action以及Action對應的View有效,資源文件已具體的action類名命名,

       如:RegisterAction.class 對應的資源文件爲

        RegisterAction.properties, 

        RegisterAction_en.properties,

        RegisterAction_cn_ZH.properties;

       資源文件與Action類放在同一目錄位置,不需要額外配置即可生效;

【Struts2國際化資源的引用方式】

 1)在View(JSP)文件中的引用方式

    使用Struts2標籤

  •         <s:text name="label.helloWorld"/>輸出國際化label.helloWorld爲資源文件中定義的key;

  •        <s:property value="%{getText('label.helloWorld')}"/>

  •        <s:textfield name="name" key="label.helloWorld"/>
            <s:textfield name="name" label="%{getText('label.helloWorld')}"/>

  •       帶參數方式

          <s:text name="label.hello">
                   <s:param>Kypulo</s:param>
            </s:text>
         使用帶參數的資源.<s:param>可以替換label.hello=hello {0}中的{0}

  •      使用校驗框時,提示信息可以國際化
       <field name="userName">
       <field-validator type="requiredstring">
        <message key=”userName.required”> </message>
       </field-validator>
    </field>

 2)在Action類中的引用方式

     

        Action的國際化主要是通過getText的三種方法實現的

    public String getText(String aTextName)

    public String getText(String aTextName,List args)

       public String getText(String aTextName,String defaultValue)

   

     如:String str2 = getText("label.hello",new String[]{"kypulo"}); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章