In this recipe, you will see how simple it is to use AJAX in JSF 2.0. For this we have built a "HelloWorld" example based on a simple button that when pressed renders a random number on the screen using the AJAX mechanism. The following screenshot is a capture of this:
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 start with a simple bean, meant to generate a random number using the java.util.Random
class. This bean looks like the following code snippet:
import java.util.Random; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "random") @SessionScoped public class RandomNumber { private Integer random = 0; Random generator = new Random( 19580427 ); public Integer getRandom() { random = generator.nextInt(); return random; } }
We go further and develop the JSF page that will call the previous bean:
<?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"> <h:head> <title>Simple JSF2.0-AJAX example</title> </h:head> <h:body> <h:form id="formID" prependId="false"> <h:outputScript name="jsf.js" library="javax.faces" target="head"/> <h:outputText id="randomID" value="#{random.random}"/> <h:commandButton id="buttonID" value="Random" onclick="jsf.ajax.request(this, event, {execute: this.id, render: 'randomID'}); return false;"/> </h:form> </h:body> </html>
That's it!
For understanding how it works, we should take a closer look at some code lines. First, we have the h:outputScript
line, which includes the JSF AJAX library into our page (this is necessary for the call to ajaxRequest
). After that, we have an outputText
component, which displays the random number from the bean. Third, we have a commandButton
, which calls ajaxRequest
and returns false
when it is clicked. An ajaxRequest
has three arguments, as follows:
this
.event
.execute
and render
properties. The first property takes a list of the ids of all the JSF components that we would like to execute, while the second property contains the IDs of all the JSF components that we want to re-render (refresh).