Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struts2 i18n in java class

I have a Struts2 web application that uses an i18n properties file for localization. The getText method works perfectly in jsp and in a action class getText("some.identifier").

But how can i use it in java-classes that are not an action-class? In other words, classes that do not have access to the getText method.

like image 837
user829237 Avatar asked Dec 27 '22 15:12

user829237


2 Answers

ResourceBundle labels =
    ResourceBundle.getBundle("MyBundle", currentLocale);
Enumeration bundleKeys = labels.getKeys();

while (bundleKeys.hasMoreElements()) {
    String key = (String)bundleKeys.nextElement();
    String value = labels.getString(key);
    System.out.println("key = " + key + ", " + 
               "value = " + value);
}

Something like this will read your resource bundle

like image 156
Umesh Awasthi Avatar answered Jan 06 '23 21:01

Umesh Awasthi


You don't actually need to re-load the bundle. You can use the following code to tap into the copy that Struts has loaded:

LocalizedTextUtil.findDefaultText(key, ActionContext.getContext().getLocale());

Keep in mind that ActionContext is thread local, so if you attempt to call this from a different thread than the one processing the request, you'll run into an error.

An overloaded form of the method takes an object array as the third parameter, if you need to pass arguments to the localized message.

like image 41
Steven Benitez Avatar answered Jan 06 '23 19:01

Steven Benitez