JSF valueChangeListener

It can be implemented with two ways:

1) For the input component we have to specify a specific bean's method in valueChangeListener attribute.

2) We need to implement ValueChangeListener and specify the same for a specific input component.

Example for 2nd way: Dynamic Jsf Web Project. Create property file and use the same configuration files used in ist way of implementing changeListener.

index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
<body>
<h:form>
 
#{msg.lan_title}: 
<h:selectOneMenu value="#{userData.localeCode}" onchange="submit()"
>
<f:valueChangeListener 
            type="LocaleChangeListener" />
    <f:selectItems value="#{userData.countries}" /> 
    </h:selectOneMenu>
    #{msg.name}: <h:inputText value="#{userData.name}" />
  <br/>
   </h:form>
</body>
</html>
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

@ManagedBean(name = "userData")
@RequestScoped
public class UserData {
private String localeCode;
private String name;

private Map<String, Object> countries;

public String getLocaleCode() {
return localeCode;
}

public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Map<String, Object> getCountries() {
countries = new LinkedHashMap<String, Object>();
countries.put("English", Locale.ENGLISH);
countries.put("French", Locale.FRENCH);
return countries;
}

public  void setCountries(Map<String, Object> countries) {
this.countries = countries;
}
}

Listener Class:

import java.util.Locale;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

public class LocaleChangeListener implements ValueChangeListener {
   @Override
   public void processValueChange(ValueChangeEvent event)
      throws AbortProcessingException {
      //access country bean directly
      UserData userData = (UserData) FacesContext.getCurrentInstance().
         getExternalContext().getRequestMap().get("userData");
      Map <String, Object> countries = userData.getCountries();
      for (Map.Entry<String, Object> entry : countries.entrySet()) {

if (entry.getValue().toString().equals(event.getNewValue().toString())) {

FacesContext.getCurrentInstance().getViewRoot()
.setLocale((Locale) entry.getValue());

}
}
}
}

Run Application:

Change Language: