Search code examples
javajsf-2internationalizationlocale

JSF resets locale


This code is totally simplified, but reproduces my problem:

BackingBean.java

public String reload(){
    System.out.println(FacesContext.getCurrentInstance()
            .getViewRoot().getLocale());
    return "test";
}

public void setLocale(){
    System.out.println("locale changed!");
    FacesContext.getCurrentInstance()
            .getViewRoot().setLocale(Locale.FRANCE);
}

test.xhtml

<h:form>
    <h:commandLink action="#{backingBean.reload}" value="reload page"/>
</h:form>
<h:form>
   <h:commandLink action="#{backingBean.setLocale}" value="change locale"/>
</h:form>

output:

en
locale changed!
fr_FR
en

If you'll change locale and then call reload method twice, locale resets to default en. What the reason of locale reset? Also, it happens only in case of forwarding to other page, if you'll change reload method to void, locale will be fr still.

public void reload(){
    System.out.println(FacesContext.getCurrentInstance()
            .getViewRoot().getLocale());
}

output:

en
locale changed!
fr_FR
fr_FR

But after 2 forwards locale will be changed back to en


Solution

  • The view locale is not remembered in the session scope. It's remembered in the view scope (heck, the view itself represents the whole view scope!).

    If you need to remember the locale in the session scope, then you need to create a session scoped managed bean and reference it as a property in <f:view locale> of master template.

    <f:view locale="#{localeManager.locale}">
    

    See also: