A first JSF 2.0-AJAX example

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:

A first JSF 2.0-AJAX example

Getting ready

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.

How to do it...

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!

How it works...

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:

  • The calling object, which is this.
  • The calling event, which is event.
  • The third argument is a little tricky. It contains the 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).

There's more...

In the next recipe, you will see another way of using AJAX in JSF 2.0.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: First_JSF_20_AJAX_example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset