The Java EE 6 Tutorial

Writing a Method to Handle a Value-Change Event

A backing bean that handles a value-change event must use a public method that accepts a value-change event and returns void. This method is referenced using the component’s valueChangeListener attribute. This section explains how to write a backing bean method to replace the ValueChangeListener implementation.

The following example tag comes from Registering a Value-Change Listener on a Component, where the h:inputText tag with the id of name has a ValueChangeListener instance registered on it. This ValueChangeListener instance handles the event of entering a value in the field corresponding to the component. When the user enters a value, a value-change event is generated, and the processValueChange(ValueChangeEvent) method of the ValueChangeListener class is invoked:

<h:inputText  id="name" size="50" value="#{cashier.name}"
     required="true">    
     <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

Instead of implementing ValueChangeListener, you can write a backing bean method to handle this event. To do this, you move the processValueChange(ValueChangeEvent) method from the ValueChangeListener class, called NameChanged, to your backing bean.

Here is the backing bean method that processes the event of entering a value in the name field on the page:

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

To make this method handle the ValueChangeEvent generated by an input component, reference this method from the component tag’s valueChangeListener attribute. See Referencing a Method That Handles a Value-Change Event for more information.