Java Reference
In-Depth Information
Listing 2.4
The doGet method with message translation
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
Locale locale = request.getLocale();
String bundleName = "fancyfoods.web.messages";
ResourceBundle resources = ResourceBundle.
getBundle(bundleName, locale);
String greeting = resources.getString("SayHello.hello");
are we?
Get right
Get translated message.
Bundles, bundles, or bundles?
You've got a few different kinds of bundles floating around at the moment, but the
resource bundles here have nothing to do with OSGi bundles—they're ordinary Java
resource bundles.
If you build the bundle and test the web page, it will work exactly as it did before. This
is reassuring if you're browsing in English, but not ideal if you're browsing in French.
To try it out: change your web browser's preferred language to French. (If you don't
want to do that, you can hardcode the locale in the getString() call in SayHello
.java .) Most pages you browse to, like Google, for example, will show French text. But
if you reload the Fancy Foods web page, the greeting is disappointingly English. To get
the Fancy Foods page to display in French, you need to provide some French transla-
To be accessible to the SayHello class, the properties files need to be loaded by the
same classloader—which (mostly) means they need to be in the same bundle. But
rebuilding JAR s is no fun, and you definitely don't want to be repackaging your exist-
ing code every time you have a new translation. You want to be able to easily drop in
support for other languages in the future.
Resource loading between bundles
We've simplified our discussion of resource loading slightly. It's possible to load re-
sources from other bundles, but it's ugly. The package containing the resource must
be exported by the providing bundle and imported by the consuming bundle. To avoid
clashes with packages in the consuming bundle, the consuming bundle shouldn't ex-
port the package it's attempting to import. Having trouble following? You won't be the
only one! We've seen this pattern used, but we definitely don't recommend it.
Luckily, this is the sort of job for which OSG i fragments are perfect. OSG i fragments are
a bit like OSG i bundles. But instead of having their own lifecycle and classloader, they
attach to a host bundle. They share the host's classloader and behave in almost every way
Search WWH ::

Custom Search