The Java EE 5 Tutorial

Retrieving Localized Messages

A web component written in the Java programming language retrieves the resource bundle from the session:

ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");

Then it looks up the string associated with the key Talk as follows:


The JSP versions of the Duke’s Bookstore application uses the fmt:message tag to provide localized strings for messages, HTML link text, button labels, and error messages:

<fmt:message key="Talk"/>

For information on the JSTL messaging tags, see Messaging Tags.

The JavaServer Faces version of Duke’s Bookstore retrieves messages using either the message or messages tag, or by referencing the message from a tag attribute using a value expression.

You can only use a message or messages tag to display messages that are queued onto a component as a result of a converter or validator being registered on the component. The following example shows a message tag that displays the error message queued on the userNo input component if the validator registered on the component fails to validate the value the user enters into the component.

<h:inputText id="userNo" value="#{UserNumberBean.userNumber}">
    <f:validateLongRange minimum="0" maximum="10" />
     style="color: red;
     text-decoration: overline" id="errors1" for="userNo"/>

For more information on using the message or messages tags, see Displaying Error Messages with the message and messages Tags.

Messages that are not queued on a component and are therefore not loaded automatically are referenced using a value expression. You can reference a localized message from almost any JavaServer Faces tag attribute.

The value expression that references a message has the same notation whether you loaded the resource bundle with the loadBundle tag or registered it with the resource-bundle element in the configuration file.

The value expression notation is var.message, in which var matches the var attribute of the loadBundle tag or the var element defined in the resource-bundle element of the configuration file, and message matches the key of the message contained in the resource bundle, referred to by the var attribute.

Here is an example from bookstore.jsp:

<h:outputText value="#{bundle.Talk}"/>

Notice that bundle matches the var attribute from the loadBundle tag and that Talk matches the key in the resource bundle.

For information on using localized messages in JavaServer Faces, see Rendering Components for Selecting Multiple Values.