duminică, 15 martie 2015

[OmniFaces utilities (2.0)] Get the application resource bundle programmatically


[OmniFaces utilities] The getResourceBundle() method returns the application resource bundle as identified by the given <var> of the <resource-bundle> in faces-config.xml. If there is no <resource-bundle> with the given <var>, then this method just returns null.

Method:
See also: Faces#getContext()

Note Do not confuse the <resource-bundle> tag with <message-bundle>. The former is used for registering custom localized static text, while the latter is used for registering custom error/info/warn messages, which are displayed by <h:message> and <h:messages>.It can be used to override the JSF default warning/error messages.

Usage:

This method is a shortcut for Application#getResourceBundle(FacesContext, String). For example, you can use it as quick solution for programmatically choose the proper entry depending on current locale. Suppose that you have the following resource bundle configuration in faces-config.xml:

<application>            
 <locale-config>
  <default-locale>fr</default-locale>
  <supported-locale>fr</supported-locale>
  <supported-locale>en</supported-locale>          
  <supported-locale>de</supported-locale>     
 </locale-config>                           
 <resource-bundle>                       
  <base-name>players.msgs.PlayerMessages</base-name>
  <var>msg</var>
 </resource-bundle>                                                                                         
</application>

Each PlayerMessages file contains a key named HELLO, as below:

PlayerMessages_en.properties
HELLO = Hello!

PlayerMessages_fr.properties
HELLO = Bonjour!

PlayerMessages_de.properties
HELLO = Hallo dort!

Further, we set the locale as fr via <f:view>, or programmatically, via Faces#setLocale().

<f:view locale="fr">...<f:view/>     

or,

import org.omnifaces.util.Faces;
...
Locale frlocale = new Locale("fr");
Faces.setLocale(frlocale);

Now, in page you can write #{msg['HELLO']}, or you can use OmniFaces shortcut in a managed bean (or other JSF artifact) to programmatically have access to the HELLO key depending on locale:

import org.omnifaces.util.Faces;
...
ResourceBundle rb = Faces.getResourceBundle("msg");
// do something with rb.getString("HELLO"); which returns, Bonjour!, in this case
...

Niciun comentariu:

Trimiteți un comentariu