How to dynamically load Resource Bundles in Struts 2


Resource bundles are objects that are characterized by a specific ‘Local’, i.e. are specific to particular geographical areas in terms of language, date format and other standards. Usually they are represented by simple properties files in the classpath with a suffix that indicates the targeted local and the application can load the appropriate resource bundle for the current local using this suffix. The resource bundles are usually all loaded during the application’s startup but sometimes there is the need to copy and load other resource bundles dynamically, without the need to restart the application.

How to load ResourceBundles dynamically with LocalizedTextUtil

A common situation in which there could be the need to load new resource bundles on the fly is a typical plugin architecture. We can imagine a web application in which components made of classes , jsp pages, CSS files and of course resource bundles can be dynamically loaded without the need to restart the application.

First of all a resource bundle file should be loaded in the classpath to make it available. If we choose to name the message bundles as global-messages then the following must be set in the configuration file:

struts.custom.i18n.resources = global-messages 

Then a classloader must be created with the URL of the path in which the bundle is stored.

        File path = new File(pluginPath);
        URL url = file.toURI().toURL();          
        URL[] urls = new URL[]{url};
        ClassLoader cl = new URLClassLoader(urls);

The classloader is then passed to the the LocalizedTextUtil setDelegatedClassLoader method:


And finally we use the addDefaultResourceBundle to load the newly copied resource bundle

        LocalizedTextUtil.addDefaultResourceBundle(pluginPath + pluginBundleName);
How to dynamically load Resource Bundles in Struts 2 last modified: 2015-04-30T16:22:53+00:00 by Mario Casari

Leave a Reply

Your email address will not be published. Required fields are marked *