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

孤者浪人 提交于 2019-12-27 12:22:24

问题


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?


回答1:


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}">


来源:https://stackoverflow.com/questions/5388426/jsf-2-0-set-locale-throughout-session-from-browser-and-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!