You need to save the selected locale in the session area and set it in the viewing mode in two places: once UIViewRoot#setLocale() immediately after changing the locale (which changes the locale of the current viewroot and, thus, is reflected in the postback, this part is not needed when you do the redirection afterwards) and once in the locale <f:view> attribute (which sets / saves the locale in subsequent queries / views).
Here is an example of what a LocaleBean looks like:
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); } }
And here's an example view should look like this:
<!DOCTYPE html> <html lang="#{localeBean.language}" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <f:view locale="#{localeBean.locale}"> <h:head> <title>JSF/Facelets i18n example</title> </h:head> <h:body> <h:form> <h:selectOneMenu value="#{localeBean.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> <p><h:outputText value="#{text['some.text']}" /></p> </h:body> </f:view> </html>
Please note that <html lang> not required for JSF to function, but it is imperative that search engines interpret your page. Otherwise, it may be marked as duplicate content, which is bad for SEO.
Connected:
BalusC Jan 28 2018-11-11T00: 00Z
source share