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