Although JSF does the internationalization of an web application automatically, like setting the right locale for UIViewRoot [2], developers can still run into some special problems:
<locale-config>
<default-locale>en</default-locale>
<supported-locale>en</supported-locale>
<supported-locale>de</supported-locale>
</locale-config>
JSF determines the locale in the following sequence:
Accept-Language) and supported localesBut it is better to suffix even the property file of the application default locale. (index_en.properties instead index.properties)
In case it is different to the JVM Default locale, the property file suffixed with the JVM locale will be used first and not the unsuffixed property file.
One possibility to set an own locale for the pages is to define the locale attribute inside the f:view Tag [4]. This can be done as hard coded string or as locale attribute of an bean.
<f:view locale="en">
<f:view locale="#{user.locale}">
But my preferred solution is to use an custom ViewHandler, which extends the JSF ViewHandler [5] or the Facelets ViewHandler [6]. Only thing to use this class is to register it in the faces config file.
<application>
<view-handler>de.icoding.CustomViewHandler</view-handler>
</application>
In order to set the locale for all pages after own conditions, just overwrite the method calculateLocale. For example in an SEO application just write:
public Locale calculateLocale(FacesContext context)
{
String path = null;
path = context.getExternalContext().getRequestServletPath();
if (path.indexOf("/de/") > 0)
return Locale.GERMAN;
else
return Locale.ENGLISH;
}
Sometimes it is neccessary to get the default locale or to iterate over all supported locales. The JSF Application class [7] provides therefore all neccessary methods:
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().getDefaultLocale();
context.getApplication().getSupportedLocales();
[1] Mojarra 1.2
[2] javax.faces.component.UIViewRoot
[3] faces-config.xml
[4] com.sun.faces.taglib.jsf_core.ViewTag
[5] javax.faces.application.ViewHandler
[6] com.sun.facelets.FaceletViewHandler
[7] javax.faces.application.Application
Johannes Hammoud Locale 01.09.2008