Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to change locale in JSF 2.0?
    text
    copied!<p>In my app, user should be able to switch the locale (the language used to render text on pages). Tons of tutorials are using FacesContext.getCurrentInstance().getViewRoot().setLocale(). For example: <a href="http://www.mkyong.com/jsf2/jsf-2-internationalization-example/" rel="noreferrer">http://www.mkyong.com/jsf2/jsf-2-internationalization-example/</a>. But, that simply doesn't work in JSF 2.0 (it did work in 1.2). The language never switches. No errors or anything. The same code worked fine in JSF 1.2. </p> <p>What is the correct and definitive approach? I have cobbled together a solution, but not sure if this is the correct one. This works fine. The language switches after user clicks on English or French. Here is code snippet to give you some idea.</p> <pre><code>@ManagedBean(name = "switcher") @SessionScoped public class LanguageSwitcher { Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); public String switchLocale(String lang) { locale = new Locale(lang); return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true"; } //getLocale() etc. omitted for brevity } </code></pre> <p>The XHTML:</p> <pre><code>&lt;f:view locale="#{switcher.locale}"&gt; &lt;h:outputText value="#{msg.greeting}" /&gt; &lt;h:commandLink value="English" action="#{switcher.switchLocale('en')}" /&gt; &lt;h:commandLink value="French" action="#{switcher.switchLocale('fr')}" /&gt; &lt;/f:view&gt; </code></pre> <p>Just to give you more info, here is the config file.</p> <pre><code>&lt;application&gt; &lt;locale-config&gt; &lt;supported-locale&gt;en&lt;/supported-locale&gt; &lt;supported-locale&gt;fr&lt;/supported-locale&gt; &lt;/locale-config&gt; &lt;resource-bundle&gt; &lt;base-name&gt;com.resources.Messages&lt;/base-name&gt; &lt;var&gt;msg&lt;/var&gt; &lt;/resource-bundle&gt; &lt;/application&gt; </code></pre> <p>Once again, this works. But, I haven't changed the locale of JSF itself by calling any API in any way. This gives me somewhat of a creepy feeling. Is this the correct way to change user's locale?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload