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:

  1. ActionClass.properties
  2. Interface.properties
  3. BaseClass.properties
  4. ModelDriven’s model
  5. package.properties
  6. Search up the i18n message key hierarchy itself
  7. Global resource properties
Refer to Struts 2 Resource Bundle documentation for detail explanation.
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

  1. com.mkyong.user.action.LoginAction.properties (found, exit, else next)
  2. com.mkyong.user.action.package.properties (found,exit, else next)
  3. com.mkyong.user.package.properties (found exit, else next)
    …keep find package.properties in every parent directory all the way to the root directory
  4. 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.

<s:text name="username" />

4. Key attribute

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

<s:textfield key="username" />

5. I18n tag

This i18n tag can get the message from a specified resource bundle that declared in the “name” attribute. In this example, it ask to get the ‘username’ message from com/mkyong/user/package.properties file.

<s:i18n name="com.mkyong.user.package" >
     <s:text name="username" />
</s:i18n>
Download full project for practice – Struts2-Resource-Bundle-Example.zip

Reference

  1. Global resource bundle in Struts2
  2. Struts 2 key attribute example
  3. Struts 2 resource bundle search order documentation
Note : You can find more similar articles at - Struts 2.x Tutorials