Wiki
Clone wikiOracle JSF Expert 1Z0-896 / Internalisation / localisation via resource bundle and Locale
Resource bundles
faces-config.xml (WEB-INF)
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <application> <locale-config> <default-locale>en</default-locale> <supported-locale>de</supported-locale> </locale-config> <resource-bundle> <base-name>org.bitbucket.paulstat.jsf.localisation.messages</base-name> <var>msgs</var> </resource-bundle> </application> </faces-config>
Bundle location
main |_ java |_ resources | |_ org | |_ bitbucket | |_ paulstat | |_ jsf | |_ localisation | |_ messages.properties |_ webapp
org.bitbucket.paulstat.jsf.localisation.messages (messages.properties)
greeting=Hello
org.bitbucket.paulstat.jsf.localisation.messages (messages_fr.properties)
greeting=Salut
f:view
<f:view locale="en"> #{msgs.greeting} </f:view> <f:view locale="fr"> #{msgs.greeting} </f:view>
f:loadBundle
<f:view locale="en"> <f:loadBundle baseName="x" var="msgs" /> #{msgs.greeting} </f:view> <f:view locale="fr"> <f:loadBundle baseName="x" var="msgs" /> #{msgs.greeting} </f:view>
**NB. If one tries to switch to a locale that's not listed in the supported locales the default will be used eg.** <f:view locale="de"> #{msgs.greeting} </f:view> The above in the case of the faces-config example defined on this page will use the default en locale
Locale switcher example
@Named @SessionScoped public class LocaleSwitcher implements Serializable { private String languageCode; public String switchLocale() { FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(languageCode)); return null; } public void setLanguageCode(String languageCode) { this.languageCode = languageCode; } public String getLanguageCode() { return languageCode; } }
<h:body> #{msgs.fixedMessage} <h:form> <h:panelGrid columns="2"> <h:commandButton immediate="true" value="English" action="#{localeSwitcher.switchLocale}"> <f:setPropertyActionListener value="en" target="#{localeSwitcher.languageCode}" /> </h:commandButton> <h:commandButton immediate="true" value="German" action="#{localeSwitcher.switchLocale}"> <f:setPropertyActionListener value="de" target="#{localeSwitcher.languageCode}" /> </h:commandButton> </h:panelGrid> </h:form> </h:body>
Updated