Struts 2 – Resource bundle example

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 tag
In text tag, set the key in “`name`” attribute.

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

##5. I18n tag
This 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值