In JSF 2.0, there are two ways of adding Ajax support to the JSF 2.0 applications. The first way was described in the previous recipe, and the second way is to use the new <f:ajax>
tag to declare Ajax support for the JSF components. We choose to develop the same "HelloWorld" example from previous recipe (a simple button that when pressed renders a random number on screen using the AJAX mechanism), to allow you to compare the two methods of using AJAX in JSF 2.0.
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
We keep the same bean from the previous recipe, and we list only the main page:
<?xml version='1.0' encoding='UTF-8' ?> <!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"> <h:head> <title>Using the f:ajax tag</title> </h:head> <h:body> <h:form id="formID" prependId="false"> <h:outputText id="randomID" value="#{random.random}"/> <h:commandButton id="buttonID" value="Random"> <f:ajax execute="formID:buttonID formID:randomID" render="formID:randomID"/> </h:commandButton> </h:form> </h:body> </html>
Notice that we have placed the <f:ajax>
tag inside the <h:commandButton>
component—this allows sending Ajax requests upon the "onclick
" action of this component. If the tag is placed inside a value holder component like <h:selectOneListbox>
, it allows sending the Ajax requests upon the "onchange" action of the component.