2
votes

Recently I've started to make i18n for JSF 1.2 web-application. Actually for this moment we need to have only two locales and instances of web-application will be deployed and configured on separate servers with same code-base.

Locale is specified at JVM level in tomcat (catalina.bat) using JAVA_OPTS, as:

-Duser.language=en -Duser.region=US

We can specify default and supported locales in faces-config.xml like this:

<locale-config>
    <default-locale>en_US</default-locale>
    <supported-locale>en_GB</supported-locale>
</locale-config>

But this configuration will use client browser specific locale instead of server default locale (what is we really need right now for our purposes).

So I was thinking about programmatically way to specify locale. First that came into my mind was:

FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.getDefault());

But if I understand correctly this way will set locale only for current user's request to webapp.

Right now I'm thinking about two ways:

  1. Set locale using FacesContext after successull user login;
  2. Specify locale configuration at the start of web-application (Not sure how to do this in JSF).

Is there any better way to configure locale for FacesContext programmaticaly at application level?

Thanks,

Yuriy

1

1 Answers

0
votes

To avoid pulling your hair, use this approach:

https://stackoverflow.com/a/12079507/1049870

I used to override PhaseListener implementing my own:

public class SessionPhaseListener implements PhaseListener {

    private static final String key = "locale";
    private static final String localeId = "es";

    @Override
    public void afterPhase(PhaseEvent event) {
        java.util.Locale locale = new java.util.Locale(localeId);

        PhaseId currentPhase = event.getPhaseId();
        if (currentPhase == PhaseId.RESTORE_VIEW) {
            viewRoot().setLocale(locale);
        } else if (currentPhase == PhaseId.RENDER_RESPONSE) {
            sessionMap().put(key, locale);
        }
    }

    private Map<String, Object> sessionMap() {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    }

    private UIViewRoot viewRoot() {
        return FacesContext.getCurrentInstance().getViewRoot();
    }
}

You can create a more smart approach.
But keep in mind that, this code is called hardly.
Read this value from an Environment Variable is the best choice.