Dynamically switching locales in a JSF application?

I have an application in which a user can dynamically switch between locales from the welcome page of my application. I see that the previous developer (inherited the code without a lot of documentation) redefined the following three methods from ViewHandler and informed me that this is required to dynamically switch Locale ... any help is much appreciated

Also, let me know if there is a better way to handle 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; } 
+4
source share
1 answer

My decision:

  • has a session-driven managed bean that contains an instance of Locale
  • have 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}">
+8
source

All Articles