How to implement session level localization in JSF instead of per request/view level selected locale memorization
P粉360266095
P粉360266095 2023-08-22 21:30:42
0
2
439

faces-config.xml:

  ru ua  

In a bean action method, I change the locale of the current view as follows:

FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("ua"));

The problem is that the ua locale only applies to requests/views, not sessions. Another request/view in the same session will reset the locale to the default ru value.

How do I apply a locale to a session?

P粉360266095
P粉360266095

reply all (2)
P粉662802882

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

    P粉426906369

    You need to store the selected locale in session scope and set it in two places: once viaUIViewRoot#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 inin thelocaleattribute (this will set/preserve the locale on subsequent requests/views).

    Here is an example of howLocaleBeanshould look:

    package com.example.faces; import java.util.Locale; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; @ManagedBean @SessionScoped public class LocaleBean { private Locale locale; @PostConstruct public void init() { locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale(); } public Locale getLocale() { return locale; } public String getLanguage() { return locale.getLanguage(); } public void setLanguage(String language) { locale = new Locale(language); FacesContext.getCurrentInstance().getViewRoot().setLocale(locale); } }

    This is an example of how the view should look:

        JSF/Facelets i18n 示例          

    This assumes that#{text}has been configured infaces-config.xmlas follows:

      com.example.i18n.text text  

    Please note thatis 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:

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!