JSF Tutorial - JSF Ajax HelloWorld Example

AJAX stands for Asynchronous JavaScript And Xml. It is a technique to use HTTPXMLObject of JavaScript to send data to server and receive data from server asynchronously.

In Ajax, Javascript code exchanges data with server, updates parts of web page without reloading the whole page.

JSF supports for Ajax call with f:ajax tag.

The following shows a simple JSF Tag.

<f:ajax execute="input-component-name" render="output-component-name" />

Tag Attributes

disabledIf true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled.
eventThe event that will invoke Ajax requests, for example "click", "change", "blur", "keypress", etc.
executeA space-separated List of IDs for components that should be included in the Ajax request.
immediateIf "true" behavior events generated are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase.
listenerAn EL expression for a method in a backing bean called during the Ajax request.
onerrorThe name of a JavaScript callback function in case of an error during the Ajax request.
oneventThe name of a JavaScript callback function to handle UI events.
renderA space-separated list of IDs of components that will be updated after an Ajax request.


The following code shows how to h:outputText tag to create an Ajax application to display user input.

The following code is from UserBean.java.

package com.java2s.common;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import java.io.Serializable;

public class UserBean implements Serializable {

  private static final long serialVersionUID = 1L;
  private String name;

  public String getName() {
    return name;

  public void setName(String name) {
    this.name = name;
  public String getSayWelcome(){
    if("".equals(name) || name ==null){
      return "Null Message";
      return "Ajax message : Welcome " + name;

The following code is from demo.xhtml.

h:inputText creates a input field box. And it uses the h:commandButton to call f:ajax.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"
        <h:inputText id="name" value="#{userBean.name}"></h:inputText>
        <h:commandButton value="Welcome Me">
           <f:ajax execute="name" render="output" />
        <h2><h:outputText id="output" value="#{userBean.sayWelcome}" /></h2>


Download Ajax_HelloWorld.zip


Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.