How to set locale dinamically via code in Struts 2

john picture john · Aug 29, 2013 · Viewed 8.7k times · Source

In my application, I have to display the content based on the locale user chosen in the configuration page. I am not using browser default locale.

when using <s:text>, it always use the default resource file.

In Struts1, I have used the below code to set default locale in my filter

session.setAttribute("org.apache.struts.action.LOCALE",locale);

How to set the user chosen locale dynamically in Struts2 ?

Answer

osmingo picture osmingo · Nov 13, 2013

This worked for me :

String language = userLocale.substring(0, 2);
String country = userLocale.substring(3, 5);
Locale locale = new Locale(language, country);
ActionContext.getContext().setLocale(locale);
session.put(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE, locale);

where the values of userLocale are of the form : fr_FR and the file for the resources is named resource_fr_FR.properties