且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-05 16:29:46

创建一个会话范围的托管 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}">