Using locales and message resource bundles

In this recipe, we will extend the previous recipe to add locales. We will add English and French locales, but you easily follow this pattern to add more locales.

Getting ready

We 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...

First we create two files named MyMessages_en.properties (this will be for the English locale) and MyMessages_fr.properties (this will be for the French locale). Both of them will have the same key, HELLO_WORLD, but the value of the key will be "Hello world!" for the English locale, and "Bonjour tout le monde!", for the French locale.

Next, we configure the message resource bundle in faces-config.xml and we set the default locale to English:

…
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<message-bundle>custom.MyMessages</message-bundle>
</application>
…

Now, we can test our locales by using the locale attribute of the f:view tag, as shown next:

<f:view locale="fr">
<f:loadBundle basename="custom.MyMessages" var="msg"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8"/>
<title>Hello World</title>
</head>
<body>
<h1><h:outputText value="#{msg.HELLO_WORLD}"/></h1>
</body>
</html>
</f:view>

How it works...

Depending on the configured or detected locale, JSF will use the _en or _fr locale and will extract and display the value of the HELLO_WORLD key.

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: Using_locales_and_message_resource_bundles.

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

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