JSF 2.0 set locale throughout session from browser and programmatically [duplicate]

Create a session scoped managed bean like follows:

@ManagedBean
@SessionScoped
public class LocaleManager {

    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);
    }

}

To set the current locale of the views, bind it to the <f:view> of your master template.

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

To change it, bind it to a <h:selectOneMenu> with language options.

<h:form>
    <h:selectOneMenu value="#{localeManager.language}" onchange="submit()">
        <f:selectItem itemValue="en" itemLabel="English" />
        <f:selectItem itemValue="nl" itemLabel="Nederlands" />
        <f:selectItem itemValue="es" itemLabel="EspaƱol" />
    </h:selectOneMenu>
</h:form>

To improve SEO of your internationalized pages (otherwise it would be marked as duplicate content), bind language to <html> as well.

<html lang="#{localeManager.language}">

Leave a Comment