webtier@glassfish.java.net

Re: Changing Locale Dynamically

From: <webtier_at_javadesktop.org>
Date: Mon, 09 Aug 2010 05:44:24 PDT

hi, actually i was replying to the example given by Mr. Marty Hall. So it may have seemed incomplete to you.

Anyways, the user presses a <h:commandButton> whose actionListener is #{person.swapLocale}. Now the swapLocale methods only duty is to change locale field in person bean like this:

@ManagedBean
@SessionScoped
public class Person implements Serializable {

    private String firstName, lastName, emailAddress;
    private boolean isEnglish = true;
    private final Locale ENGLISH = Locale.ENGLISH;
    private Locale SPANISH = new Locale("es");

   //getters and setters for firstName, lastName, emailAddress

    public void swapLocale(ActionEvent event) {
        System.out.println("[swapLocale] Setting isEnglish to " + !isEnglish);
        isEnglish = !isEnglish; //swap boolean field isEnglish

    }
}

notice the above method just sets the boolean field to true or false.

Now there is another method in person bean:

@ManagedBean
@SessionScoped
public class Person implements Serializable {
   .
   .
   .

 public Locale getLocale() {
        
        if (isEnglish) {
           
            return (ENGLISH);
        } else {
           
            return (SPANISH);
        }
    }

}

so basically #{person.locale} which runs the getLocale() method returns the currently selected locale.

So finally in the phaselistener beforePhase method, the #{person.locale} is read, and set as the current locale.

Now for any page in the application, whether the page swaps locale or not, the phaselistener beforePhase will check the #{person.locale} value and set it as current locale. This was done as the original post had problem with locale when a page was refreshed/reloaded in the browser.
[Message sent by forum member 'nash_era']

http://forums.java.net/jive/thread.jspa?messageID=479668