The Java EE 5 Tutorial

Implementing Value-Change Listeners

A ValueChangeListener implementation must include a processValueChange(ValueChangeEvent) method. This method processes the specified value-change event and is invoked by the JavaServer Faces implementation when the value-change event occurs. The ValueChangeEvent instance stores the old and the new values of the component that fired the event.

The NameChanged listener implementation is registered on the name UIInput component on the bookcashier.jsp page. This listener stores into session scope the name the user entered in the text field corresponding to the name component. When the bookreceipt.jsp page is loaded, it displays the first name inside the message:


"Thank you, {0} for purchasing your books from us."

Here is part of the NameChanged listener implementation:

...
public class NameChanged extends Object implements
     ValueChangeListener {

     public void processValueChange(ValueChangeEvent event)
        throws AbortProcessingException {
    
        if (null != event.getNewValue()) {
            FacesContext.getCurrentInstance().
                getExternalContext().getSessionMap().
                    put("name", event.getNewValue());
        }
    }
}

When the user enters the name in the text field, a value-change event is generated, and the processValueChange(ValueChangeEvent) method of the NameChanged listener implementation is invoked. This method first gets the ID of the component that fired the event from the ValueChangeEvent object. Next, it puts the value, along with an attribute name, into the session map of the FacesContext instance.

Registering a Value-Change Listener on a Component explains how to register this listener onto a component.