| [ Team LiB ] |
|
Recipe 24.4 Creating a ResourceBundle as a Java ClassProblemYou want to create a ResourceBundle as a Java class. SolutionCreate a class that extends java.util.ListResourceBundle. DiscussionIf 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 ListResourceBundlepackage 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( )){
//Prints out key: "Welcome"
out.println((String) enum.nextElement( ));
out.println("<br /><br />");
}//while
See AlsoThe Javadoc for ListResourceBundle: http://java.sun.com/j2se/1.4.1/docs/api/java/util/ListResourceBundle.html; Recipe 24.3 on creating a ResourceBundle as a properties file. |
| [ Team LiB ] |
|