リソース・バンドルを使用してプロパティ・ファイルからメッセージを取得するには、Struts 2リソース・バンドルの検索順序を理解する必要があります。

リソースバンドルの検索順序

リソースバンドルは次の順序で検索されます。

  1. ActionClass.properties

  2. Interface.properties

  3. BaseClass.properties

  4. ModelDrivenのモデル

  5. package.properties

  6. i18nメッセージ鍵階層自体を検索する

  7. グローバルリソースプロパティ

詳細については、Struts 2のhttp://struts.apache.org/2.1.8/docs/localization.html[Resource Bundle documentation]を参照してください。

こんにちはStruts 2、あなたはあまりにも多くの検索順序が含まれており、プロパティファイルが見つからない場合はコストパフォーマンスがあります。

実際には、上記の順序でプロパティファイルを編成することは非常に不可能です。

ActionClass.properties



package.properties



Global resource properties

など、一般的に使用されている検索オーダーで十分であるはずはありません。下の図を参照してください:


Struts 2リソースバンドル、title = "struts2-resource-bundle"

…​keep find package.properties in every parent directory all the way to
the root directory
. Find the

global
resource properties

if you configure it in your application

Understand this search order can give you more confident to decide the
correct folder for properties file.

Get the resource bundle

Few examples to access the resource bundle :


P.S ‘

username.required

‘ and ‘

username

‘ are the key in a properties
file.

1. Action class

In Action class, you can extends the ActionSupport and get the resource
bundle via getText(‘key’) function.

...
public class LoginAction extends ActionSupport{
    ...
    public void validate(){
        if("".equals(getUsername())){
            addFieldError("username", getText("username.required"));
        }
    }
}

2.プロパティタグ

プロパティタグでは、getText( ‘key’)を使用します。

<s:property value="getText('username')"/>

3.テキストタグ

テキストタグでは、 “name”属性にキーを設定します。

<s:text name="username"/>

4.キー属性

UIコンポーネントのKey属性は特別な機能を持っています。このリンクの//struts2/struts-2-key-attribute-example/[key属性の例]で詳細を確認してください。

<s:textfield key="username"/>

5.I18nタグ

このi18nタグは、 “name”属性で宣言された指定されたリソースバンドルからメッセージを取得できます。この例では、

com/mkyong/user/package.properties

ファイルから ‘username’メッセージを取得するよう求められます。

<s:i18n name="com.mkyong.user.package" >
     <s:text name="username"/>
</s:i18n>

実践のための完全なプロジェクトをダウンロードする –

Struts2-Resource-Bundle-Example.zip

リファレンス

  1. link://struts2/how-to-configure-global-resource-bundle-in-struts-2/[グローバル

Struts2のリソースバンドル]。 link://struts2/struts-2-key-attribute-example/[Struts 2のキー属性

リソースバンドルの検索順序のドキュメント]