Jay Jay - 15 days ago 7
Java Question

ResourceBundle is unable to load properties file from package inside a webapp

I am working on refactoring a huge collection of code in an enterprise-scaled application.

The first step I want to take is to localize the log messages, so I decided to use the

that I saw when I was reading the source code of Apache Tomcat.

The basic idea is to declare a file named
LocalString.properties
in the packages and define log messages in them. So in a way, this localizes the Strings to scope of that package only, so that it looks like:

Application
`----src
| `----main
| `----java
| `----package
| `----BusinessAction.java
| `----LocalStrings.properties
`----pom.xml


And an object of this
StringManager
is instantiated as:

private static final StringManager sm = StringManager.getManager("package");





This is constructor of the
StringManager
class.

/**
* Creates a new StringManager for a given package. This is a
* private method and all access to it is arbitrated by the
* static getManager method call so that only one StringManager
* per package will be created.
*
* @param packageName Name of package to create StringManager for.
*/
private StringManager(String packageName) {
String bundleName = packageName + ".LocalStrings";
try {
bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault());
} catch( MissingResourceException ex ) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if( cl != null ) {
try {
bundle = ResourceBundle.getBundle(
bundleName, Locale.getDefault(), cl);
} catch(MissingResourceException ex2) {
// Ignore
}
}
}
// Get the actual locale, which may be different from the requested one
if (bundle != null) {
locale = bundle.getLocale();
}
}


This works absolutely fine when used in a standalone application, but is causing issues when used in a web application.

I don't understand why the bundle fails to load on the first hand, but in the catch block, I can definitely tell that it is because the classloader is an instance of
WebappClassloader
.

What mistake I am making here? Also, what would be the good ways to load this property file?

Answer

The reason it fails is simply that the LocalStrings.properties file is not in your war file. In a Maven project, resources are supposed to be under src/main/resources. Not src/main/java. Maven will simply ignore resources under src/main/java.