How to implement session level localization in JSF instead of per request/view level selected locale memorization
P粉360266095
2023-08-22 21:30:42
<p><code>faces-config.xml</code>:</p>
<pre class="brush:php;toolbar:false;"><application>
<locale-config>
<default-locale>ru</default-locale>
<supported-locale>ua</supported-locale>
</locale-config>
</application></pre>
<p>In a bean action method, I change the locale of the current view as follows: </p>
<pre class="brush:php;toolbar:false;">FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("ua"));</pre>
<p>The problem is that the <code>ua</code> locale only applies to requests/views, not sessions. Another request/view in the same session will reset the locale to the default <code>ru</code> value. </p>
<p>How do I apply a locale to a session? </p>
I see that the problem is also related to the .properties file name. Java's Locale code (lowercase) such as: en_gb But the Locale automatically generated by Netbeans is lowercase_uppercase, for example: messages_en_GB.properties Change it to: messages_en_gb.properties Then it should work fine - if you've tried everything
You need to store the selected locale in session scope and set it in two places: once via
UIViewRoot#setLocale()
Immediately after changing the locale (This will change the locale of the current view root so that it is reflected in subsequent requests; if you perform a redirect later, this part is unnecessary), and once in<f:view>
in thelocale
attribute (this will set/preserve the locale on subsequent requests/views).Here is an example of how
LocaleBean
should look:This is an example of how the view should look:
This assumes that
#{text}
has been configured infaces-config.xml
as follows:Please note that
<html lang>
is not required for JSF functionality, but is mandatory for search engine explanation pages. Otherwise, it may be marked as duplicate content, which is bad for SEO.See also: