The Java EE 5 Tutorial

Writing a Method to Handle a Value-Change Event

A backing bean that handles a value-change event must be a public method that accepts a value-change event and returns void. This method is referenced using the component’s valueChangeListener attribute.

The Duke’s Bookstore application does not have any backing bean methods that handle value-change events. It does have a ValueChangeListener implementation, as explained in the Implementing Value-Change Listeners section.

For illustration, this section explains how to write a backing bean method that can replace the ValueChangeListener implementation.

As explained in Registering a Value-Change Listener on a Component, the name component of the bookcashier.jsp page 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.

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 bookcashier.jsp page:

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

The page author can make this method handle the ValueChangeEvent object emitted by a UIInput component by referencing this method from the component tag’s valueChangeListener attribute. See Referencing a Method That Handles a Value-change Event for more information.