1

Is there a way to implement a viewParam that can change the locale eg.

http://example.com/p1.jsf?lang=en or http://example.com/p2.jsf?lang=fr

perhaps without repeating

<f:metadata>
    <f:viewParam name="lang" value="#{localeManager.locale}" />
</f:metadata>

in every xhtml page (perhaps by intercepting every xhtml request, check the value of the lang parameter and update the locale)

A similar question was asked and answered but involves JSF2 @ManagedProperty and to be honest I din't not understand the answer.

Any thoughts?

Community
  • 1
  • 1
  • @Ravi: that is exactly the problem i think, it can not be added in the template. it is discussed [here](http://stackoverflow.com/questions/7344056/jsf2-how-achieve-site-wide-viewparam-handling-policy-using-a-template) – Dimitris Tsamitros Apr 27 '13 at 07:35
  • ah..now I get it..So since you use CDI, you can Inject the http parameter like explained in this post [depedency-inject-request-parameter-with-cdi](http://stackoverflow.com/questions/13239975/depedency-inject-request-parameter-with-cdi) and works for me instead of @ManagedProperty. – Ravi Kadaboina Apr 27 '13 at 15:53
  • You can't use `@ManagedProperty` in CDI. The custom producer implemented in the solution from @Ravi is your best bet – kolossus Apr 29 '13 at 04:05

1 Answers1

0

I worked out a solution that did not involve CDI.

I set the locale after the restore view phase of the JSF life cycle.

@SuppressWarnings("serial")
public class LifeCycleListener implements PhaseListener {

  ...

  public void afterPhase(PhaseEvent event) {
    if (event.getPhaseId() == PhaseId.RESTORE_VIEW) {

      // let's try first to get the language from the request parameter  
      // and if it is a supported language then put it to session
      String reqParamLang = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("lang");

      if (reqParamLang != null) {
        Iterator<Locale> localeIterator = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
        while (localeIterator.hasNext()) {
          Locale locale = localeIterator.next();
          if (reqParamLang.equals(locale.toString())) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("lang", reqParamLang);
            Logger.getLogger(this.getClass().getName()).info("will change locale to " + locale);
          }
        }
      } 

      // get the language from the session and if available then set the locale 
      String sessionLang = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("lang");

      if (sessionLang != null) {
          FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(sessionLang));
      }
    }
  }
}