Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF setLocale doesn't work appropriately

I implemented internationalization into my JSF app as described here.

But I encountered a problem: When I change the locale all the texts on my page change. But then if I click a navigation-link to get to another page the locale jumps back to standard locale!

I think I miss something here. So I provide my code below and hope you can help:

LocaleBean.java:

    @ManagedBean(name="locale")
    @SessionScoped
    public class LocaleBean {

    private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

    public Locale getLocale() {
        return locale;
    }

    public void setLanguage(String language) {
        locale = new Locale(language);
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
    }

    public String getLanguage() {
        return locale.getLanguage();
    }
    }

JSF Part (it's part of my template):

    <h:outputText value=" #{text['common.language']}: " /> 
        <h:selectOneMenu value="#{locale.language}" onchange="submit()">
            <f:selectItem itemValue="de" itemLabel="Deutsch" />
            <f:selectItem itemValue="en" itemLabel="English" />
        </h:selectOneMenu>

faces-config.xml:

<?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>de</default-locale>
                <supported-locale>en</supported-locale>
           </locale-config>
       <resource-bundle>
        <base-name>org.dhbw.stg.wwi2008c.mopro.ui.text</base-name>
        <var>text</var>
       </resource-bundle>
     </application>
</faces-config>

I then Text.java from the tutorial and only changed bundle-path.

Here my directory:

If something important is missing ask for it please.

like image 227
Sven Avatar asked Jan 20 '11 09:01

Sven


1 Answers

FacesContext is request scoped instance. so your value would be set for that particular request only.

add on xhtml

<f:view locale="#{locale.locale}">

OR:

Register a view Handler
in faces-config.xml

 <application>
           ...
       <view-handler>com.yourcompany.MyLocaleViewHandler</view-handler> 

and

public class MyLocaleViewHandler extends ViewHandler {

    private final ViewHandler base;


    @Override
    public Locale calculateLocale(FacesContext context) {
      //fetch the session scoped bean and return the
      LocaleBean bean = (LocaleBean ) context.getExternalContext().getRequest().getSession().getAttribute("locale");//this line is not tested.
      return locale;
    }
      //other stuff..


    }
like image 159
jmj Avatar answered Oct 22 '22 23:10

jmj