Struts 2 – Resource bundle example

来源:互联网 发布:php 设置跨域请求头 编辑:程序博客网 时间:2024/05/22 05:05

To use resource bundle to retrieve the message from properties file, you have to understand the Struts 2 resource bundle search order :

Resource bundle search order

Resource bundle is searched in the following order:

  • ActionClass.properties
  • Interface.properties
  • BaseClass.properties
  • ModelDriven’s model
  • package.properties
  • Search up the i18n message key hierarchy itself
  • Global resource properties

Hi Struts 2, you search too much, there are too many search orders involved and cost performance if the properties file is not found.
In practice, it’s quite impossible to organize your properties file as order above. So, just understand few common used search orders should be enough : ActionClass.properties, package.properties and Global resource properties. See the below picture :

Struts 2 resource bundle
If a com.mkyong.user.action.LoginAction want to get a message via resource bundle, it will search

  • com.mkyong.user.action.LoginAction.properties (found, exit, else next)
  • com.mkyong.user.action.package.properties (found,exit, else next)
  • com.mkyong.user.package.properties (found exit, else next)
  • …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. property tag

In property tag, use the getText(‘key’).

<s:property value="getText('username')" />##3. text tagIn text tag, set the key in “`name`” attribute.

##4. Key attributeThe Key attribute of UI component has special function, check detail in this key attribute example.

##5. I18n tagThis i18n tag can get the message from a specified resource bundle that declared in thename” attribute. In this example, it ask to get the ‘username’ message from `com/mkyong/user/package.properties` file.




“`

0 0