Loading message resource bundles in JSF

Suppose that we have a message resource bundle with the following content (message resource bundles are simply property files with key/value pairs) named myMessages.properties (its content is not relevant here):

HELLO_WORLD = Hello world message!

In this recipe, you will see how to load and use such a file into a JSF page.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...

For loading the message resource bundle we use the core tag f:loadBundle. This loads the bundle and stores it in the request scope. For example:

<f:loadBundle basename="custom.MyMessages" var="msg"/>

Usually, this line appears after an <f:view> tag and the attribute basename indicates the location and name of the resource bundle, while the variable's name is specified by the var attribute of the f:loadBundle element (for example, msg).

Now you can display a localized string from our message resource bundle with a JSF component.

<h:outputText value="#{msg.HELLO_WORLD}"/>

The resource bundle is also registered in faces-config.xml, as shown next:

<application>
<message-bundle>custom.MyMessages</message-bundle>
</application>

How it works...

When JSF finds the f:loadBundle tag, it tries to load the specified message resource bundle and assign a variable to it, through the var attribute. Now, this var can be used globally in JSF page for writing ELs to indicate the desired messages. Usually, this is done by indicating the message's key.

Note

Notice that we have placed the MyMessages.properties under the source folder of our application. This will help JSF 2.0 to find it without an explicit entry in the faces-config.xml descriptor.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Load_the_message_resource_bundle_in_JSF.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset