Struts 2 - リソースバンドルの例

Struts 2 –リソースバンドルの例

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

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

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

  1. ActionClass.properties

  2. Interface.properties

  3. BaseClass.properties

  4. ModelDrivenのモデル

  5. package.properties

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

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

詳細な説明については、Struts 2Resource Bundle documentationを参照してください。

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

実際には、上記の順序でプロパティファイルを整理することはまったく不可能です。 したがって、ActionClass.propertiespackage.propertiesGlobal resource propertiesなどの一般的に使用される検索順序で十分であることを理解してください。 以下の写真を参照してください。

Struts 2 resource bundle

com.example.user.action.LoginActionがリソースバンドルを介してメッセージを取得したい場合、検索します

  1. com.example.user.action.LoginAction.properties (found, exit, else next)

  2. com.example.user.action.package.properties (found,exit, else next)

  3. com.example.user.package.properties (found exit, else next)
    …keep find package.properties in every parent directory all the way to the root directory

  4. アプリケーションで構成する場合は、global resource propertiesを見つけます

この検索順序を理解することで、プロパティファイルの正しいフォルダーを決定する自信が得られます。

リソースバンドルを取得する

リソースバンドルにアクセスするいくつかの例:

P.S ‘username.required‘ and ‘username‘ are the key in a properties file.

1. アクションクラス

Actionクラスでは、ActionSupportを拡張し、getText( ‘key’)関数を介してリソースバンドルを取得できます。

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

2. プロパティタグ

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

3. テキストタグ

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

4. キー属性

UIコンポーネントのKey属性には特別な機能があります。このkey attribute exampleで詳細を確認してください。

5. I18nタグ

このi18nタグは、「name」属性で宣言された指定されたリソースバンドルからメッセージを取得できます。 この例では、com/example/user/package.propertiesファイルから「username」メッセージを取得するように求められます。


     

練習用の完全なプロジェクトをダウンロード–Struts2-Resource-Bundle-Example.zip