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 ?
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
You set the locale in the following way in Struts 2:
ActionContext ctx = ActionContext.getContext();
if (ctx != null)
{
ctx.setLocale(locale);
}
You can also use the I18nInterceptor.
The Struts2 internationalization interceptor i18n
could be used to dynamically change the current user locale to the user specific locale for the user's session.
"Or, alternatively, only for the current request (since XWork 2.1.3)"
by making an HTTP request and supplying a request parameter request_locale
with the value of the locale like "en_US"
which create a locale for English, US.
This locale is saved in the session by default under "WW_TRANS_I18N_LOCALE"
attribute and used as a current locale during the user session. The current locale is also pushed into the ActionContext
map by this interceptor upon every request. This allows framework components that support localization all utilize the ActionContext
's locale.
More detailed description with example code you could find in the docs for I18n Interceptor.
An interceptor that handles setting the locale specified in a session
as the locale for the current action request. In addition, this
interceptor will look for a specific HTTP request parameter and set
the locale to whatever value is provided. This means that this
interceptor can be used to allow for your application to dynamically
change the locale for the user's session or, alternatively, only for
the current request (since XWork 2.1.3). This is very useful for
applications that require multi-lingual support and want the user to
be able to set his or her language preference at any point. The locale
parameter is removed during the execution of this interceptor,
ensuring that properties aren't set on an action (such as
request_locale
) that have no typical corresponding setter in your
action.
For example, using the default parameter name, a request to
foo.action?request_locale=en_US
, then the locale for US English is
saved in the user's session and will be used for all future requests.
If there is no locale set (for example with the first visit), the
interceptor uses the browser locale.