views:

47

answers:

1

I have an application where the user can dynamically switch between locales from the welcome page of my application. I see that the earlier developer (inherited the code without much documentation) has overridden the following three methods from ViewHandler and tells me that this is required for dynamic switching of the Locale...any help is highly appreciated

Also, do let me know if there is a better way of handling this

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;
}
+5  A: 

My solution is:

  • 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}">
Bozho
Thank you for the suggestion. I have been told that (after posting the question) if jsf view was already created restore view will render the CURRENT view in same locale it was created before even though the locale has been changed...does your suggestion handle that?
Pangea
Restore-view is a phase in the jsf lifecycle, and as such, is called on every request. So the next request you make (after a redirect, for instance), you'll have your new locale.
Bozho