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.4. Creating a ResourceBundle as a Java Class

Problem

You want to create a ResourceBundle as a Java class.

Solution

Create a class that extends java.util.ListResourceBundle .

Discussion

If your application requires more functionality than a static properties file can provide (Recipe 24.3), you can create your ResourceBundles as Java classes: java.util.ListResourceBundle types. For instance, a particular resource might need to select its translation information from a database.

Example 24-4 includes the same information as the properties file in the prior recipe. However, its key/value pairs are stored in the form of a two-dimensional Object array. This class is stored in the same place as the .properties files in WEB-INF/i18n.

Example 24-4. Storing language information in a ListResourceBundle

package com.jspservletcookbook;           

import java.util.ListResourceBundle;
 
public class WelcomeBundle_es_ES extends ListResourceBundle {
     
         static final Object[][] contents = {
  
         {"Welcome", "Hola y recepción"}
     };
         
         public Object[][] getContents( ) {
         return contents;
     }
     
 }

This code snippet from a servlet shows how you could use this class.

Example 24-5. Calling a ListResourceBundle method from a ResourceBundle created as a Java class

<!-- inside servlet goGet( ) or doPost( ) method, for instance --> ResourceBundle bundle = ResourceBundle.getBundle( "i18n.WelcomeBundle_es_ES"); //Call inherited ListResourceBundle getKeys( ) method java.util.Enumeration enum = bundle.getKeys( ); while (enum.hasMoreElements( )){ ...

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