Internationalization with JSF 2.0

Application internationalization is the process of developing an application in such a way that it can be adapted to n number of languages without requiring a recompilation of the code.

To accomplish internationalization, all text-based elements within the application [such as header, footer, error messages, and form labels] are to be extracted outside the source code (via properties files) and retrieved dynamically (via faces-config).

*This example does not take into consideration languages that require right to left formatting.

default.xhtml

 

faces-config.xml

 

messages.properties

login.welcome=Welcome!

 

messages_fr_FR.properties

login.welcome=Bienvenue!

 

LanguageBean.java
package com.international;  import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent;   @ManagedBean(name="language") @SessionScoped public class LanguageBean implements Serializable{      	//If no serialVersionUID is declared, the JVM will generate a default SerialVersionUID which can cause         //InvalidClassExceptions during the deserialization process 	private static final long serialVersionUID = 1L; 	 	private String locale;                  public String getLocale() { 		return locale; 	}  	public void setLocale(String locale) { 		this.locale = locale; 	}                  public MapString, Object> getCountriesInMap() { 		return map; 	} 	         private static MapString,Object> map;         static{                 //add as many locale codes as you like here                 //language is first and required, country (2nd code) is not required                 map = new LinkedHashMapString,Object>(); 		map.put("English", new Locale("en")); 		map.put("French", new Locale("fr","FR")); 	}  	public void countryLocaleCodeChanged(ValueChangeEvent vce){ 		 		String newLocale = vce.getNewValue().toString();                  		//iterate over each entry in the map         for (Map.EntryString, Object> entryValue : map.entrySet()) {                  	if(entryValue.getValue().toString().equals(newLocale)){         		//(Locale)entryValue.getValue() = new Locale('fr')         		FacesContext.getCurrentInstance()         			.getViewRoot().setLocale((Locale)entryValue.getValue());         		         	}         }  	}  }