Using ResourceBundles to handle messages in Java –

No Gravatar

Java has a couple of concepts that are used as best practices in web applications that can be very useful even if you don’t intend to use them for their strict purpose. The first is a properties file and the second is internationalization (i18n – 18 letters between the i and the n).
Properties files are simple key=value files. They contain records that are in this format generally:

my.key=My Value

Internationalization is a concept that allows an application to move it’s labels of field names, descriptions, etc. to be encoded in properties files with a specific extension representing the language. These follow the 2-letter ISO 3166 country code extensions. These are very useful in web applications and allow you to extract messages at will using both manual methods as well as tag libraries.

An example of the manual method is shown below:

ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources");
String adminId = messages.getString("adminuserid");
String adminPassword = messages.getString("adminpassword");

This bit of code will extract the value of the adminuserid property from the file and place it’s value in the adminId field, and the same with the adminPassword field.

An example of using the jstl fmt taglib in order to display a message is shown below:

<fmt:message key="label.userId"/>

This bit of code will extract the value of the label.userId property and render it on the screen.

Hope this helps.

Be Sociable, Share!