miercuri, 1 iulie 2015

[OmniFaces utilities 2.1] Get a string for the given key searching declared resource bundles


[OmniFaces utilities] The getBundleString() method gets a string for the given key searching declared resource bundles, order by declaration in faces-config.xml. If the string is missing, then this method returns ???key???.

Method:
Usage:

Let's suppose that we have the below two resource bundles:

The content of  msgs.UserMessages for English is:

The content of  msgs.AdminMessages for English is:
Notice that the NAME key appears in both!

Now, in faces-config.xml, we declare both resource bundles, as below (for the "user" messages we have attached the var named, user, and for the "admin" messages, the var named, admin):

<application>
 <locale-config>
  <default-locale>en</default-locale>
  <supported-locale>en</supported-locale>
  <supported-locale>fr</supported-locale>
 </locale-config>
 <resource-bundle>
  <base-name>msgs.UserMessages</base-name>
  <var>user</var>
 </resource-bundle>
 <resource-bundle>
  <base-name>msgs.AdminMessages</base-name>
  <var>admin</var>
 </resource-bundle>
</application>

Now, you can use both resource bundles in the application views by indicating the proper var. For example, a dummy usage is below:

<h:outputText value="#{admin['NAME']}"/><br/>
<h:outputText value="#{admin['ROLE']}"/><br/>
<h:outputText value="#{admin['SECURITY']}"/><br/>
<h:outputText value="#{user['NAME']}"/><br/>
<h:outputText value="#{user['SURNAME']}"/><br/>

Now, programmatically speaking, we can locate a key in the current resource bundles like below - keep in mind that OmniFaces will inspect the resource bundles in the order of their declaration in faces-config.xml, which means that in this case it will first inspect the UserMessages, and if the searched key is not present there, it will inspect the AdminMessages). The result are listed for both locales:

// 'First Name' or 'Nom', from UserMessages
Faces.getBundleString("NAME");
// 'Last Name' or ' Nom de Famille', from UserMessages
Faces.getBundleString("SURNAME");
// 'administrator' or 'administrateur', from AdminMessages
Faces.getBundleString("ROLE");
// 'low' or 'faible', from AdminMessages
Faces.getBundleString("SECURITY");

If you reverse the order of UserMessages and AdminMessages in faces-config.xml, then we will have:

// 'Complete Name' or 'nom et surnom', from AdminMessages
Faces.getBundleString("NAME");
// 'Last Name' or 'Nom de Famille', from UserMessages
Faces.getBundleString("SURNAME");
// 'administrator' or 'administrateur', from AdminMessages
Faces.getBundleString("ROLE");
// 'low' or 'faible', from AdminMessages
Faces.getBundleString("SECURITY");

Niciun comentariu:

Trimiteți un comentariu