Tuesday, August 07, 2007

Detect Browser Language In JSF

The webapp developed so far (build 0.0.5) allows users to select from a dropdown list which language they would like the website to exhibit - English (default), French, and Spanish. However, language selection can be automated by reading the default language of the client's web browser.
In JSF application, you'll most probably do request processing in a managed bean, so that's where language detection should happen. Every web request arrives with information about the web browser in a request header. This information is available to the application via an ExternalContext object:

// Get the application context
FacesContext facescontext = FacesContext.getCurrentInstance();
// Get the request headers
Map requestHeaders = facescontext.getExternalContext().getRequestHeaderMap();
// Read the supported languages
String languages = (String) requestHeaders.get("Accept-Language");
String lang = Options.INTL_ENGLISH;
if(languages != null) {
if(languages.contains("es"))
lang = Options.INTL_SPANISH;
else if(languages.contains("fr"))
lang = Options.INTL_FRENCH;
else // default
lang = Options.INTL_ENGLISH;
}

To change the default language for Firefox, open the options dialog (Tools | Options...) and click the Advanced tab. Select Languages and choose which language to use. You need to restart Firefox for the changes to take effect. Most websites should then begin to detect your preferred language and present data in that language (if they are internationalized). Try Google, for example.