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.5. Using the ResourceBundle in a Servlet

Problem

You want a servlet to dynamically display a "Welcome" message to visitors depending on their locale.

Solution

Use the servlet to access the translated text dynamically from a ResourceBundle.

Discussion

Once you have added ResourceBundles to the web application, then servlets can use them to dynamically display text based on the user's locale.

Tip

Remember, the web application stores ResourceBundles as .properties files (text) or Java classes.

Example 24-6 uses a ResourceBundle with a basename of "WelcomeBundle." It is stored in WEB-INF/i18n, so its fully qualified name is i18n.WelcomeBundle.

Example 24-6. A servlet uses a to dynamically display translated text

package com.jspservletcookbook;import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    
      //Get the client's Locale
      Locale locale = request.getLocale( );

      ResourceBundle bundle = ResourceBundle.getBundle(
        "i18n.WelcomeBundle",locale);

      String welcome =  bundle.getString("Welcome");
   
    
      //Display the locale
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );

      out.println("<html><head><title>"+welcome+"</title></head><body>");
      
      out.println("<h2>"+welcome+"</h2>"); out.println("Locale: "); out.println( locale.getLanguage( )+"_"+locale.getCountry( ...

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