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?
Asked
Active
Viewed 2.0k times
1 Answers
40
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}">

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
What if I add add tr that is not in Locale class definition such as Locale.CANADA,Locale.GERMAN. I added in faces-config.xml ;
en tr however it doesnt work :/ – Günay Gültekin Jan 02 '13 at 08:59