JSF应用中的动态语言环境切换?

4
我有一个应用程序,用户可以在我的应用程序的欢迎页面上动态切换语言环境。我发现之前的开发人员(继承了没有太多文档的代码)已经重写了ViewHandler中的以下三个方法,并告诉我这对于动态切换Locale是必需的...非常感谢您的帮助。
此外,请让我知道是否有更好的处理方法。
public Locale calculateLocale(FacesContext facescontext)
{
    Locale userLocale = LocaleManager.getInstance().getCurrentLocale();
    if (userLocale != null)
    {
        return userLocale;
    }
    else
    {
        return delegate.calculateLocale(facescontext);
    }
}

public void renderView(FacesContext facescontext, UIViewRoot uiviewroot)
        throws IOException, FacesException {
    uiviewroot.setLocale(LocaleManager.getInstance().getCurrentLocale());
    delegate.renderView(facescontext, uiviewroot);
}
public UIViewRoot createView(FacesContext facescontext, String s)
{
    UIViewRoot view = delegate.createView(facescontext, s);
    view.setLocale(LocaleManager.getInstance().getCurrentLocale());
    return view;
}
1个回答

9

我的解决方案是:

  • have a session-scoped managed-bean that holds a Locale instance
  • have the the following button (or link) for each supported language:

    <h:commandButton action="#{localeBean.changeLocal}">
         <f:setPropertyActionListener target="#{localeBean.selectedLanguage}" 
                  value="en" />
    </h:commandButton>
    
  • set the current locale based on the passed language (new Locale(lang))

  • in your template(s) use <f:view locale="#{localeBean.currentLocale}">

谢谢您的建议。我被告知(在发布问题后),如果JSF视图已经创建,则恢复视图将以相同的语言环境呈现当前视图,即使语言环境已更改...您的建议是否处理此问题? - Aravind Yarram
Restore-view 是 JSF 生命周期中的一个阶段,因此在每个请求中都会被调用。因此,在您进行下一个请求(例如重定向后)时,您将拥有新的区域设置。 - Bozho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接