O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

24.6. Using the ResourceBundle in a JSP

Problem

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

Solution

Use the JSTL tags from the formatting library.

Discussion

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" />

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

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

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

</body>
</html>

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).

Tip

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required