How do I detect the locale for an application based on the initial browser request and use it throughout the browsing session untill the user specifically changes the locale and how do you force this new locale through the remaining session?
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}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With