JSF 2.0 and Resource Bundles example

In this tutorial, we demonstrate the use of resource bundle to display messages in JSF 2.0. For maintainability concern, it’s always recommended to put all the messages in properties file, instead of hard-code the message in page directly.

1. Properties File

Create a properties file, contains message for the page, and put it into the project’s resource folder, see figure below

messages.properties

message = This is "message"
message.test1 = This is "message.test1"
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1}

Project folder structure.

jsf2-resource-bundles-folder

2. Using Resource Bundles

There are two ways to load the properties file into JSF 2.0.

1. Global Resource Bundle
To load the properties file globally, so that all the jsf pages can access the messages. You can create a “faces-config.xml” file and declare the properties file explicitly.

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
     <application>
	  <resource-bundle>
		<base-name>com.mkyong.messages</base-name>
		<var>msg</var>
	   </resource-bundle>
     </application>
</faces-config>

2. Local Resource Bundle
To load the properties file locally, or for specified page only. Declare the <f:loadBundle /> tag in the page that need to access the message in the messages.properties.

<f:loadBundle basename="com.mkyong.messages" var="msg"/>

3. JSF 2.0 Pages

In this case, the messages.properties file is given a name of “msg“, to access the message, just use “msg.key“.

hello.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">
 
    <h:body>
      <h2>JSF 2.0 and Resource Bundles Examples</h2>
      <ol>
 
   	<li><h:outputText value="#{msg.message}" /></li>
 
    	<li><h:outputText value="#{msg['message.test1']}" /></li>
 
    	<li><h:outputText value="#{msg['message.test2']}" /></li>
    	<li><h:outputText value="#{msg['message.test2']}" escape="false" /></li>
 
    	<li><h:outputText value="#{msg['message.test3']}" /></li>
    	<li><h:outputText value="#{msg['message.test3']}" escape="false" /></li>
 
    	<li>
 	     <h:outputFormat value="#{msg['message.param1']}">
		<f:param value="param0" />
	     </h:outputFormat>
	</li>
	 <li>
	     <h:outputFormat value="#{msg['message.param2']}">
	    	<f:param value="param0" />
	    	<f:param value="param1" />
	     </h:outputFormat>
	  </li>
    	</ol>
    </h:body>
</html>

4. How it works?

Example 1
A normal way to access the message.

<h:outputText value="#{msg.message}" />
 
//properties file
message = This is "message"

Example 2
For a key that has a dot “.” as name, you can’t use the normal way #{msg.message.test1}, it will not work. Instead, you should use bracket like #{msg[‘message.test1′]}.

<h:outputText value="#{msg['message.test1']}" />
 
//properties file
message.test1 = This is "message.test1"

Example 3
To display HTML tag in the message, just add the “escape” attribute and set it to false.

<h:outputText value="#{msg['message.test2']}" />
<h:outputText value="#{msg['message.test2']}" escape="false" />
<h:outputText value="#{msg['message.test3']}" />
<h:outputText value="#{msg['message.test3']}" escape="false" />
 
//properties file
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"

Example 4
For a parameter message, just use the <h:outputFormat /> and <f:param / > tag.

<h:outputFormat value="#{msg['message.param1']}">
   <f:param value="param0" />
</h:outputFormat>
<h:outputFormat value="#{msg['message.param2']}">
   <f:param value="param0" />
   <f:param value="param1" />
</h:outputFormat>
 
//properties file
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1}

5. Demo

URL : http://localhost:8080/JavaServerFaces/hello.jsf

jsf2-resource-bundles-example

Download Source Code

Download it – JSF-2-Resource-Bundles-Example.zip (8KB)
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Google()

  • tolga

    i tried it with my project but the change on dropdown list does not fire the countryLocaleCodeChanged method. I clearly spoored all the things but it doesnt work. only if i change default properties file in faces-config. any idea?

  • Subrahmanya

    A couple of small changes needed in the source of hello.xhtml for it to work;

  • http://www.slideshare.net/rafaelogerg/logans-roadhouse-coupons-coupons-available-here roger

    These are in fact impressive ideas in concerning blogging.
    You have touched some good factors here. Any way keep up wrinting.

  • http://www.slideshare.net/andyvargasfgvl/apple-tv-coupon-code-coupons-available-now donald

    I am sure this piece of writing has touched all the internet people, its really really
    pleasant piece of writing on building up new blog.

  • Dipashri Tikle

    Hi Mkyong,
    I am facing an issue in

    &lt;ice:panelConfirmation&gt;

    .
    The sample code is as follows :

    &lt;ice:panelConfirmation id=&quot;sampleId&quot; acceptLabel=&quot;yes&quot; cancelLabel=&quot;cancel&quot; message=&quot;hello &lt;i&gt;there&lt;/i&gt;&quot; title=&quot;sampleTitle&quot; /&gt;

    I expect the html tag should render here but this is also not able to render html tags and printing it as normal text in output . Which is not expected . Please help me in both these metioned scenerios . Waiting for the responce .

    • Dipashri Tikle

      I have tried entity code here for

       &lt;i&gt; and &lt;i&gt;

      . But it’s not working …. :(

  • Dipashri Tikle

    Hi , I am using in a xhtml file . The sample code is as follows :

     &lt;ice:panelGroup id=&quot;sampleGroup&quot;&gt;
    &lt;ice:dataTable id=&quot;sampleTable&quot; value=&quot;#{sampleBean.variable}&quot; var=&quot;sampleVar&quot; &gt;
    &lt;ice:column&gt;&lt;ice:outputText escape=&quot;false&quot; value=&quot;#{sampleVar.text}&quot; /&gt;&lt;/ice:column&gt;
    &lt;/ice:dataTable&gt;
    &lt;/ice:panelGroup&gt;

    in “text” (used in ) ,I am using few html tags . It’s not able to render those tags and displaying those tags as text in output .

  • Dipashri Tikle

    Hi , I am using in a xhtml file . The sample code is as follows :

    in “text” (used in ) ,I am using few html tags . It’s not able to render those tags and displaying those tags as text in output . (e.g. Hello Techie )

  • ravi kumar

    Hi Mkyong,

    I wanted to print the copyright info in my console. I have the message in Properties file.
    Now i can able to print the copyright info as it is in the message using ouput tag. Here my problem is i want to edit that message to update the year in it. Please help on it ASAP….

    Thanks In Advance…………

  • Juan

    Hola, como estas una pregunta, como incorporas esos messages dentro de un ManagedBean?????

    • Migue

      Hola Juan,

      Para acceder al fichero de mensajes yo hago lo siguiente:

      private static ResourceBundle mensajesBundle;

      public static String getTextoMensaje( String clave, String… params ) {
      if (mensajesBundle == null) {
      FacesContext fContext = FacesContext.getCurrentInstance();
      mensajesBundle = ResourceBundle.getBundle(
      fContext.getApplication().getMessageBundle(),
      fContext.getViewRoot().getLocale()
      );
      }
      String resultado = null;
      try {
      String mensaje = mensajesBundle.getString( clave );
      if (params.length != 0) {
      resultado = MessageFormat.format( mensaje, (Object[]) params );
      } else {
      resultado = mensaje;
      }
      } catch (Exception e) {
      resultado = “???” + clave + “???”;
      }
      return resultado;
      }

      Te recomiendo que guardes este código en una clase de ayuda en tu código tipo FacesUtils de manera que sea accesible no solo por un bean en concreto sino por cualquiera.

      Si lo que te interesa es acceder a las etiquetas, en vez de a los mensajes, solo tienes que cambiar lo siguiente:

      if (etiquetasBundle == null) {
      FacesContext fContext = FacesContext.getCurrentInstance();
      etiquetasBundle = fContext.getApplication().getResourceBundle( fContext, “etiquetas” );
      }

      Donde “etiquetas” es el nombre que tengas definido en el faces-config.xml:

      es

      es.corporate.project.web.i18n.etiquetas
      etiquetas

      es.corporate.project.i18n.mensajes

      Espero te sirva. Un saludo!

      • Migue

        La última parte no ha salido muy bien. El fichero faces-config.xml quedaría así:

        es

        es.corporate.project.i18n.etiquetas
        etiquetas

        es.corporate.project.i18n.mensajes

  • gill

    Hi Mykyong.

    Great article. I have one may be silly question. How do you read the property file in the backing bean.

  • http://e-booksland.com Faceofjock

    Thanks for this helpful website

  • Uday

    This example is pretty clear,
    If i want to use this resource-bundle for different locale’s in my java code,
    How can i make user of it.

  • Muhammad Ather

    Hey Mkyong, great Tutorials. I am stuck in a problem

    I added messages.properties in my org.training.java package and it contains the same content as your above mentioned messages.properties file and I configure it in faces-config file and loaded on xhtml file, as u explained above but when i run my page the browser renders HTTP Status 500 Error, what am i doing wrong? Below is what i wrote in faces-config file:

    &lt;application&gt;
     &lt;resource-bundle&gt;
      &lt;base-name&gt;org.trainings.mkyong.messages&lt;/base-name&gt;
      &lt;var&gt;msg&lt;/var&gt;
     &lt;/resource-bundle&gt;
    &lt;/application&gt;

    And on my xhtml page i did this:

    &lt;h:outputText value=&quot;#{msg.message}&quot; /&gt;
    • jk

      I placed my messeges.properties in resources folder too and write in faces-config
      org.trainings.mkyong.messages
      this does not work
      I correct base-name to
      resources.org.trainings.mkyong.messages
      and it work fine.

  • Pingback: JSF 2 internationalization example()

  • mauro

    it is possible use the resource-bundle for get localizated erros messages for hibernate validation???????
    help me please
    mauro

  • vasanth

    Very good articles in Mkyong.com. It’s the first stop for JSF doubts.
    I needed help. I am doing internationalization and running into few issues.

    In our project we are using maven2 and JSF1.2(still).

    I modified the pom.xml in such a way that properties file would come and sit in “classes” folder i.e. WEB-INF/classes/xyz.properties

    “Local resource bundle” is working fine.

    “Global resource bundle” is not working fine.
    My faces.config.xml snippet looks like the following

    &lt;application&gt;
    		&lt;locale-config&gt;
    		&lt;default-locale&gt;en&lt;/default-locale&gt;
    		&lt;supported-locale&gt;fr_FR&lt;/supported-locale&gt;
    		&lt;/locale-config&gt;
    		&lt;message-bundle&gt;appMessages&lt;/message-bundle&gt;
    		&lt;resource-bundle&gt;
    			&lt;base-name&gt;com.vasanth.app.internationalization.xyz&lt;/base-name&gt;
    			&lt;var&gt;message&lt;/var&gt;
    	   &lt;/resource-bundle&gt;
    	&lt;/application&gt;

    My test.jsp:

    ..
    ..

    I have placed the xyz.properties file in
    src/main/resources/com/vasanth/app/internationalization

  • akshat

    Great tutorial!! :)

    One question :- when I load the resource-bundle locally in a page…should I add the entries in faces-config.xml? Or directly use it in the xhtml page.

    I tried using it directly, did not work :/

  • Michael

    Thanks heaps. I have to admit that your style of explaining and going through the JSF basics suits me best.

  • Minh Dzung

    I’d like to say that your article help me a lot.
    Almost articles I google don’t mention about resource bundle hierarchical message key.
    They always give example such as
    //properties file
    message_param1 = This is “message.param1″ – {0}
    message_param2

    Once again, you rock! You help me a lot!
    Thank you very much!

    • http://www.mkyong.com mkyong

      Welcome, good to know that it works to you.

  • satya

    Hi,

    Nice explanation and nice presentation including workspace structure

    regards
    Satya

  • heppa

    Hey there…

    Nice presentation, but I am missing a point, to be honest. The way you show resource bundles was kind of already working with JSF 1.2. Since 2.0, there is also locales and libraries. Maybe you could also state something about this?

    Apart from that a good tut for starters! Thank you!

  • Pingback: JSF 2.0 Tutorials()

  • turboliux

    nice tutorial!
    Little bit confusing in “4. How it work?” (Should be works instead of work) but it’s ok.
    Keep it up! :)

    • http://www.mkyong.com mkyong

      Thanks for correction

  • Pingback: Customize validation error message in JSF 2.0()

  • Pingback: JSF 2 dataTable example()

  • roger

    If I were you I should make it a little bit more clear that step 1 and 2 are alternatives.

    You might also want to work a little bit on your English:

    “In this tutorial, it shows the use of resource bundle to display the messages in the JSF 2.0. ”

    ->

    “In this tutorial, we demonstrate the use of a resource bundle to display messages in JSF 2.0.” or

    “In this tutorial, we show how to use a resource bundle to display messages in JSF 2.0.”

    Basically, you don’t seem to understand how to use articles in English. You use them where they shouldn’t be used and you omit them where they are needed.

    • http://www.mkyong.com mkyong

      Thanks for your kind comment and correction

      • gera

        @Mkyong
        One of the less confusing things for me while trying to learn how to load a

        DBResourceBundle.class

        is the style of English used in a Tutorial.

        Your Tutorial is fine, Your English is fine, Everything is fine.

        Great Website!

        Thank you very much

        • Upendra Naidu

          I aggreed with you, As long as we understand the english and the articals, It is OK, The impartant thing to undestand here is that this site is for explaing techinical things but not to teach english proficiency.

          Hi Mkyong, Good Articals and Tutorials. Go Ahead, Keep it up.