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

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.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net