A simple JSF2+AJAX example

In this blog, I go over a very simple JSF2+AJAX example and show how one can spy on the inner workings with the TCP monitor and debugger.

JSF2 will provide a standard mechanism for adding AJAX capabilities to JSF applications. Jim Driscoll has this example, but it is a bit odd—the property getter is actually a mutator. Here is a more run-of-the-mill example. The code is at the Kenai site for the upcoming Core JSF 3rd edition in the ch01/login-ajax directory. I used Eclipse with the Glassfish v3 plugin and the most current JSF2 module in Glassfish (2.0.0 B8).

We want to process a login and show a welcome message upon success, all without a page flip.

The bean class is straightforward. (For simplicity, the code don't actually check the login credentials.)

package com.corejsf;

import javax.faces.model.ManagedBean;
import javax.faces.model.SessionScoped;

@ManagedBean(name = "user")
public class UserBean {
   private String name = "";
   private String password;

   public String getName() { return name; }
   public void setName(String newValue) { name = newValue; }

   public String getPassword() { return password; }
   public void setPassword(String newValue) { password = newValue; }
   public String getGreeting() { return name.length() == 0 ? "" : "Welcome to JSF2 + AJAX, " + name + "!"; }

In the JSF page, we need to include the AJAX JavaScript library, with the following incantation:

  <h:outputScript name="jsf.js" library="javax.faces" target="head" />

(The library name has recently changed. In the Public Review spec, it was called ajax.js.)

To avoid nested IDs for the components that are updated asynchronously, use the prependId attribute in the form:

  <h:form prependId="false">

Give IDs to the inputText and outputText components.

  <h:inputText value="#{user.name}" id="name"/>
  <h:inputSecret value="#{user.password}" id="password"/>
  <h:outputText id="out" value="#{user.greeting}"/>

Then define the login button as follows:

  <h:commandButton value="Login" type="button"
    onclick="jsf.ajax.request(this, event, {execute: 'name password', render: 'out'}); return false;"/>

(The function was called javax.faces.Ajax.ajaxRequest in the PR spec.)

Note that this is not a submit button. When the button is clicked, the onclick handler is executed, but the form data is not posted back. There is no page flip. The jsf.ajax.request method makes an asynchronous request to the server and receives instructions on which components to update. (Details below.)

The values of the execute and render keys are space-separated ID lists. The components on the execute list go through all parts of the JSF lifecycle except for “Render Response”. Those on the render list go through “Render Response”.

The input components must be on the execute list, so that the bean's setters are invoked. (This is where Jim's example was a bit confusing. His “Count” button isn't updating the model. It just forces the property getter to be invoked.)

Now let's spy on what goes on under the hood. Execute the View Source command of your browser. (If you use Eclipse, it defaults to using an internal browser without a View Source command. That is not good. Select Window → Web Browser → Default System Web Browser from the menu and run the app again.)

Note the element

<script type="text/javascript" src="/ch01-login-ajax/faces/javax.faces.resource/jsf.js?ln=javax.faces">

This is the result of the outputScript tag. You can spy on the script by pointing your browser to


It contains a documentation of the request function that is more up-to-date than the Public Review spec:

In Eclipse or Netbeans, it is easy to run the app server in debug mode and set a breakpoint in the bean's getters and setters.

That's how I found out what needs to go to the execute list. (In Jim's example, he added a submit button to that list, but it does actually no good in this case.)

As David Geary and myself were experimenting with different settings, David questioned whether there was any AJAX going on at all. To settle the question, I figured out how to set up the TCP monitor in Eclipse. (In Netbeans, this is much easier, but David says most people he meets prefer Eclipse :-)) Search for TCP in the Window→Preferences dialog...

Then point your browser to http://localhost:10333/ch01-login-ajax (or whichever port you set up). You'll see the requests and responses.

For example, here is the response when clicking the Login button.

<?xml version="1.0" encoding="utf-8"?>
<partial-response><changes><update id="out">
<![CDATA[<span id="out">Welcome to JSF2 + AJAX, Cay!</span>]]></update>
<update id="javax.faces.ViewState"><![CDATA[j_id5:j_id6]]>`````</update></changes></partial-response>

As you can see, the response contains instructions how to update the output field.

Note that the output field must be present in the page. I tried to avoid the greeting property by using the rendered attribute:

  <h:outputText id="out" rendered="#{user.name != ''}"  
    value="Welcome to JavaServer Faces, #{user.name}!"/>

That did not work—the AJAX update was not able to add the component since it didn't exist on the client. (Use View Source to verify that...)

For a chuckle, try a user name of ]]>. With today's version (2.0.0 B8), it doesn't work. Of course, that's a bug—someone was insufficiently paranoid about CDATA.

What can one learn from all this?

With JSF development, you need all the friends you can get :-)