background image

Providing Localized Messages and Labels

<< Java Platform Localization Classes | Setting the Resource Bundle >>
<< Java Platform Localization Classes | Setting the Resource Bundle >>

Providing Localized Messages and Labels

Providing Localized Messages and Labels
Messages and labels should be tailored according to the conventions of a user's language and
region. There are two approaches to providing localized messages and labels in a web
application:
Provide a version of the JSP page in each of the target locales and have a controller servlet
dispatch the request to the appropriate page depending on the requested locale. This
approach is useful if large amounts of data on a page or an entire web application need to be
internationalized.
Isolate any locale-sensitive data on a page into resource bundles, and access the data so that
the corresponding translated message is fetched automatically and inserted into the page.
Thus, instead of creating strings directly in your code, you create a resource bundle that
contains translations and read the translations from that bundle using the corresponding
key.
The Duke's Bookstore applications follow the second approach. Here are a few lines from the
default resource bundle messages.BookstoreMessages.java:
{
"TitleCashier", "Cashier"},
{
"TitleBookDescription", "Book Description"},
{
"Visitor", "You are visitor number "},
{
"What", "What We're Reading"},
{
"Talk", " talks about how Web components can transform the way you develop
applications for the Web. This is a must read for any self respecting Web developer!
"},
{
"Start", "Start Shopping"},
Establishing the Locale
To get the correct strings for a given user, a web application either retrieves the locale (set by a
browser language preference) from the request using the getLocale method, or allows the user
to explicitly select the locale.
The JSTL versions of Duke's Bookstore automatically retrieve the locale from the request and
store it in a localization context (see
"Internationalization Tag Library" on page 215
). It is also
possible for a component to explicitly set the locale by using the fmt:setLocale tag.
The JavaServer Faces version of Duke's Bookstore allows the user to explicitly select the locale.
The user selection triggers a method that stores the locale in the FacesContext object. The
locale is then used in resource bundle selection and is available for localizing dynamic data and
messages (see
"Localizing Dynamic Data" on page 390
):
<h:commandLink id=
"NAmerica" action="storeFront"
actionListener=
"#{localeBean.chooseLocaleFromLink}">
<h:outputText value=
"#{bundle.english}" />
Providing Localized Messages and Labels
The Java EE 5 Tutorial · September 2007
468