faces-config.xml:
<application>
<locale-config>
<default-locale>ru</default-locale>
<supported-locale>ua</supported-locale>
</locale-config>
</application>
In a bean action method, I’m changing the locale in the current view as follows:
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("ua"));
The problem is that ua Locale is applied, but only per request/view and not for session. Another request/view within the same session resets the locale back to default ru value.
How can I apply the locale for session?
You need to store the selected locale in the session scope and set it in the viewroot in two places: once by
UIViewRoot#setLocale()immediately after changing the locale (which changes the locale of the current viewroot and thus get reflected in the postback; this part is not necessary when you perform a redirect afterwards) and once in thelocaleattribute of the<f:view>(which sets/retains the locale in the subsequent requests/views).Here’s an example how such a
LocaleBeanshould look like:And here’s an example of the view should look like:
Which assumes that
#{text}is already configured infaces-config.xmlas below:Note that
<html lang>is not required for functioning of JSF, but it’s mandatory how search bots interpret your page. Otherwise it would possibly be marked as duplicate content which is bad for SEO.See also: