[ Team LiB ] Previous Section Next Section

Recipe 24.6 Using the ResourceBundle in a JSP


You want to dynamically display text in the JSP according to the locale of the request.


Use the JSTL tags from the formatting library.


The JSTL's formatting tags make it easy to dynamically display text based on the browser's language setting. Example 24-7 makes available the formatting and core JSTL tags with the taglib directive. Then it uses the fmt:setBundle tag to specify the i18n resources that will be used by the page (the localization context).

Example 24-7. Using the formatting tags to display a locale-sensitive message in a JSP
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<fmt:setBundle basename="i18n.WelcomeBundle" />

<head><title> <fmt:message key="Welcome" /></title></head>

<h2><fmt:message key="Welcome" /></h2>

Locale: <c:out value=
  "${pageContext.request.locale.language}" />_<c:out value=
    "${pageContext.request.locale.country}" />


Just like the servlet code in the prior recipe, the tag dynamically uses the WelcomeBundle resource based on the request's locale. In other words, if the browser's locale is "es_ES," a Spanish locale, then the fmt:message tags uses the keys and values from the WelcomeBundle_es_ES properties file or Java class (however it is implemented).

If you set the localization context as a context-param element in the deployment descriptor, the JSP does not have to use the fmt:setBundle tag. See Recipe 24.13.

In the JSP, the code:

<fmt:message key="Welcome" />

is replaced by the value of the "Welcome" key in the chosen ResourceBundle file ("Hola y recepción"). The result of requesting this JSP looks just like Figure 24-3 in Recipe 24.5.

See Also

Recipe 24.5 on using the ResourceBundle in a servlet; Chapter 23 on the JSTL; the Javadoc for ResourceBundle: http://java.sun.com/j2se/1.4.1/docs/api/java/util/ResourceBundle.html.

    [ Team LiB ] Previous Section Next Section