JSF 2.0 通过浏览器和编程方式在整个会话中设置语言环境

2022-01-18 00:00:00 locale internationalization java jsf jsf-2

如何根据初始浏览器请求检测应用程序的区域设置,并在整个浏览会话期间使用它,直到用户专门更改区​​域设置,以及如何在剩余会话中强制使用此新区域设置?

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?

推荐答案

创建一个会话范围的托管 bean,如下所示:

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

}

要设置视图的当前语言环境,请将其绑定到主模板的 <f:view>.

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

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

要更改它,请将其绑定到具有语言选项的 <h:selectOneMenu>.

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>

要提高国际化页面的 SEO(否则会被标记为重复内容),请将语言绑定到 <html>.

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

相关文章