Monday, April 19, 2010

Sample Code: Handling Value Change Events in JSF

There are two type of events that are generated by JSF components
• Value Change Events
• Action Events
One way to handle the events is to implement the appropriate listener. For handling action events javax.faces.event.ActionListener must be implemented and for handling value-changed events javax.faces.event.ValueChangedListener must be implemented. It must also be noted that action events are generated by controls that implement the ActionSource interface where as value-change events are generated by those controls that implement the EditableValueHolder interface.
Following is a class that implements ValueChangedListener. As can be seen that when implementing this listenen the processValueChange method must be implemented

package stu;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

@ManagedBean(name="questionsController")
@SessionScoped
public class QuestionsController implements ValueChangeListener{
private String data;

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
data = event.getNewValue().toString();
}
public QuestionsController() {

}

}
Registering a Listener with EditableValueHolder can be done either by specifying the type i.e. fully qualified name of class that implements ValueChangeListener (using the type attribue), or by registering an instance of ValueChangeListener implementation with the component (using binding attribute). This information is provided within the valueChangeListener tag nested inside the components tag with which the listener is to be registered.

<h:body>
<h:form>
Hello from Facelets
<h:selectOneRadio>
<f:selectItem itemValue="a" itemLabel="a"></f:selectItem>
<f:selectItem itemValue="b" itemLabel="b"></f:selectItem>
<f:valueChangeListener binding="#{questionsController}"></f:valueChangeListener>
</h:selectOneRadio>
<h:commandButton value="error" action="error"></h:commandButton>
</h:form>
</h:body>

As can be seen that error page displays the output, the code for which is given below

<h:body>
Invalid Login
<h:outputLabel value="#{questionsController.data}"></h:outputLabel>
</h:body>

No comments:

Post a Comment