java JSF 2.0 在整个会话期间从浏览器和以编程方式设置区域设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5388426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:53:39  来源:igfitidea点击:

JSF 2.0 set locale throughout session from browser and programmatically

javajsfjsf-2internationalizationlocale

提问by Farouk Alhassan

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?

如何根据初始浏览器请求检测应用程序的语言环境并在整个浏览会话中使用它,直到用户特别更改语言环境,以及如何在剩余的会话中强制使用此新语言环境?

回答by BalusC

Create a session scoped managed bean like follows:

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

@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>主模板的 。

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

To change it, bind it to a <h:selectOneMenu>with language options.

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

<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.

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

<html lang="#{localeManager.language}">