Monday, August 20, 2012

Use resource bundle messages files out of the classpath

Target audience for this post is have a little bit of experience in using resource bundle for localization in Java. Usually, you will have to put the relevant message files(Which contains key=value pairs) in the classpath and you will have to give the location when get the resource bundle object. For example, to get your Messages_en.properties file you implement following code.
Locale locale = new Locale( "en" );
String bundleBase = "myPackage.localizedMsgs.i18n.Messages";
ResourceBundle resourceBundle = ResourceBundle.getBundle( bundleBase, locale );
But in that case, if you wanted to do a change on any message you will have to rebuild the war file (if you are developing a web app) and deploy it. But I came across with a scenario where you need to keep message files out of the war and let user to do changes when necessary. Following example shows how to load such files on to the application context. Message files location is = ${catalina.base}/conf/messages/ so, the en message file will be, ${catalina.base}/conf/messages/Messages_en.properties Edit the catalina.properties file which is located in ${catalina.base}/conf/ directory. Add the folder location to the shared.loader parameter.
------file: catalina.properties-----

shared.loader=${catalina.base}/conf/messages/
Then the files in that location will be directly accessible on your application. Use following code and initialize the resource bundle with those files.
Locale locale = new Locale( "en" );
String bundleBase = "Messages";
ResourceBundle resourceBundle = ResourceBundle.getBundle( bundleBase, locale );
This was working perfectly for me. Thanks for reading.

2 comments:

  1. i've done a internalization in GWT.But when i deployed.i didn't find the .properties inside the .war file.if want to change the content in properties file how to add...Plz advise...


    Thanks & Regards
    Karthick V

    ReplyDelete