[ Team LiB ] |
![]() ![]() |
Recipe 24.6 Using the ResourceBundle in a JSPProblemYou want to dynamically display text in the JSP according to the locale of the request. SolutionUse the JSTL tags from the formatting library. DiscussionThe 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).
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 AlsoRecipe 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 ] |
![]() ![]() |