Over a million developers have joined DZone.

Introduction to Ajax4JSF

DZone's Guide to

Introduction to Ajax4JSF

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Java Server Faces provided a Component Based Architecture for building User Interface Components for the Web Application. Ajax aims in providing Faster Response to the Client Applications by reloading only the needed Data. Wouldn't be nice to take the advantages of both Jsf and Ajax for developing Robust Web Applications. Ajax4Jsf provides solution for this. It is the integration of Java Server Faces with Ajax (which stands for Asynchronous JavaScript and Xml), thereby providing Ajax Support to the Jsf UI Components. This article attempts to provide an overview of the Ajax4Jsf Framework which is now an open Source Project in the JBoss Community.

  • Introduction to Ajax4Jsf
  • Exploring the Ajax4Jsf Library
  • Sample Application on Ajax4Jsf

2) What is Ajax4Jsf?

Before trying into Ajax4Jsf, it is wise to know about the various pieces of technologies upon which Ajax4Jsf is built. From the name of the Framework itself, one should identity that Ajax (Asynchronous JavaScript and Xml) and Jsf (Java Server Faces), the most two popular technologies, are embedded within it. Let us look into these two technologies first, before delving deep into Ajax4Jsf.

Java Server Faces provides a Component Based Framework for managing and developing User Interface Components in a Web Application. It also provides rich set of Functionalities that includes Event Handling, Configuring the Page Navigation Mechanism, Validation of Client Data, Data Conversion etc. It also provides a Pluggable Architecture wherein Developers can develop their own Custom User Interface Components and plug with ease into the Framework. One of the major features of the Jsf Framework is that it is not targeted to one type of Clients. It means that apart from Html Browser Clients for the Desktop, it is even possible to have Wml Browser Clients for the mobile phones.

Ajax which stands for Asynchronous JavaScript and Xml is not new. A smarter way of using the existing standards/technologies like JavaScript, Xml and Html gave birth to Ajax. Using Ajax, it is possible for the JavaScript Code to directly communicate with the Server End. The request and the response data between Client and Server is exchanged in Xml Format. One of the major advantages of using Ajax is that it is speed up the performance of the Web Application by loading only the portion of the Web Page in consideration, thereby establishing better results. For more information and applications of Ajax, refer http://jsf.javabeat.net/articles/2007/06/ajax-functionality-in-custom-java-server-faces-component.

Now it's time to have a look on Ajax4Jsf. As one would have guessed, Ajax4Jsf is a Framework, which, when included in a Web Application will add Ajax support for the Jsf Components. Since Jsf is a Component Based Framework, it is easy to Construct Additional Components which provided Ajax Support to the Jsf Pages. So, all the Components in the Ajax4Jsf Library are nothing but extension to Jsf Components. The transparent use of Java Script Code along with Xml Http Request Objects will be taken care by the Framework itself which means that Developer don't have to mix Java Script Code into their Application. Let us look into the Internals of the Ajax4Jsf Framework in detail in the next section.

3) Ajax4Jsf Internals

Before looking into the Ajax4Jsf internals, let us look briefly into the Architecture of Jsf. It is worth to look into the Architecture of Jsf first before getting into the details.

In Java Server Faces, whenever a Client makes a Request comes for a Resource, it is intercepted by the Faces Servlet (as represented by the javax.faces.webapp.FacesServlet). This Servlet will make the Client Request that will go through the six different Life cycle Phases like View Restoration Phase, Applying the Request Values, Validation of User Inputs, Updating the Model Objects, Execution of Application and finally Response Rendering. Ajax4Jsf is a framework that adds support to existing Jsf Application. In fact, Ajax4Jsf Framework is implemented as a Filter thereby adding JavaScript function and XmlHttpObject dependencies to the existing Jsf Components. But when the Request is a Ajax4Jsf Request, the whole things changes. Specially, whenever a Request is made by the User, a Java Script Event is fired which is processed by the Ajax Engine that usually sits in the Client Side. Now it's the Job of the Ajax Engine to submit to original Request to the Ajax4Jsf, which means that the Request will be intercepted by the Ajax4Jsf Filter. Then the Conversion of the Data to the Xml Format will take place here through the various Xml Filters after which the Request is forwarded to the original Faces Servlet thereby making the Request to go through Several Phases.

In the Ajax4Jsf Framework, there are so-called Ajax Containers which represents a Tree of Components along with Request Values that is encoded and decoded during Ajax Request and Response. It is because of the availability of Ajax Engine in the Client updates to portion of Areas in the Web Page is possible.

4) Exploring the Ajax4Jsf Library

This section is dedicated in looking over the Ajax4Jsf Tags for the various Functionalities. Most of the Tags in this Library provide an alternate means for representing the same functionality as achieved by Jsf Tags. Either of the two Tags can be used in such a situation. It is hard to classify the set of tags based on the functionalities and the following sections attempt to provide a brief description about the most commonly used Tags along with some sample snippets.

4.1) Region Tag

Not all the Client Data in a Page is needed by the Server for processing. In most of the cases, only Data from a Portion of a Page is sufficient to process that particular request. This is where the Ajax Region Tag comes into picture. It is a kind of Container Tag meaning that it can hold other Type of Component tags. When components are defined in this Tag, only the values for these components are processed in the Server Side when an Ajax Request is made.

By default, if there is no definition for a Region Tag in a JSP page, then the whole of the JSP Page will be taken as the Ajax Region. Multiple Region Tags within the same Page is also possible.

Following code snippet shows the usage of this Tag:

<a4j:region id = "employeeRegion" actionListener = "#{manager.processEmpData}">
<!-- Other Set of Components -->

<a4j:region id = "stockRegion" actionListener = "#{manager.processStockData}">
<!-- Other Set of Components -->

In the above code, we have defined two regions, one is the 'employeeRegion' and the other one is the 'stockRegion'. Whenever an Ajax Request is made for the 'employeeRegion' (or 'stockRegion'), then the portion of Data available only with the 'employeeRegion' will be sent to the server (Manager. processEmpData() method) for processing.

4.2) Command Button Tag

This represents a Button Component and can be used to fire Action Events on the Server. This is very similar to the Jsf Command Button Tag, but instead of generating Jsf Request, an Ajax Request will be generated upon Button Click which will be intercepted by the Ajax Engine. There is a useful attribute called 'oncomplete' which can contain JavaScript Code or a JavaScript Function that will get executed once the response comes from the Server.

All the Events like Change Events, Key Events, and Mouse Events etc are applicable to this Tag through the usage of various attributes. The property called 'reRender' will take a comma separated list of Component Identifier that will get re-rendered as soon as control comes from the Server back to the Client.

Following is the code snippet demonstrating the usage of Command Button Tag:

<a4j:commandButton id = "clickButton" value = "Click Me"
action = "#{Listener.processClickRequest}" oncomplete = "jsFunction()">
reRender = "CompId1, CompId2, CompId3"

In the above code, whenever the Button with value 'Click Me' is activated, the method processClickRequest() within the Listener class gets invoked. After that the Components as represented by the Component Ids (CompId1, CompId2 and CompId3) will get the updated value from the Server. Then finally, the Java Script function jsFunction() as mentioned in the 'oncomplete' attribute will be invoked.

4.3) Command Link Tag

There is no great difference between the Command Button and the Command Link apart from their representation, as both manifests a form of Action Components. All the properties that are applicable to Command Button are applicable to Command Link also.

The following code snippet shows the usage of this Component:

<a4:commandLink id = "myLink" value = "This is my Link"
action = "Listener.processMyLink">

4.4) Media Output Tag

While the output Text Tag is used to pour normal Character contents, this Tag is used to render Rich Contents back to the Client in the form of Image, Audio or Video. To achieve this, the attribute 'createContent' must provide a method which takes two arguments of type java.io.OuputStream and java.lang.Object. Following is the usage for the same:

<a4j:mediaOutput id = "telephone" element = "img" mimeTye = "image/png"
createContent = "#{ImagePainter.drawImage}">

In the above code snippet, the attribute 'element' can take these possible set of values ('anchor', 'image', 'object', 'applet') which represents the name of the Html Element that should be used to render this image. Note that 'mimeType' being pointed to image/png file, since we are going to create an array of bytes from an image file that is of type png. Considering the 'createContent' attribute, it takes a Jsf EL Expression whose method takes OutputStream and Object as arguments. Following is the code for the same:


package net.javabeat.articles.ajax4jsf.introduction;

import java.io.*;

public class ImagePainter {

private String fileName = "telephone.png";

public void drawImage (OutputStream output, Object object) throws IOException{

File file = new File(fileName);
byte byteArray[] = new byte[1000];

FileInputStream inputStream = new FileInputStream(file);
int bytesRead = inputStream.read(byteArray);
output.write(byteArray, 0, bytesRead);
if (inputStream != null){

Note that the OutputStream object which is passed as an argument to the drawImage() method should be populated with the byte array pointing to the Image Resource.

4.5) Keep Alive Tag

Assume that a Managed Bean Component has been declared with 'Request' scope in the Configuration File with the help of <managed-bean-scope> tag. Then the Life-time of this Bean Object is valid only for the Current Request. Any attempt to make a reference to the Bean Object after the Request ends will throw in Illegal Argument Exception by the Server because the Bean Object is now invalid.

To avoid these kinds of Exceptions being happening, we can depend on the Keep Alive Tag which is used to maintain the state of the Whole Bean object among subsequent Request. Following is the code snippet for the same:

<a4j:keepAlive beanName = "#{manager.empBean}">

Note that the attribute must point to a legal Jsf EL Expression which resolves to a Managed Bean instance. For example for the above code the Class definition may look like this,


class Manager{

private EmployeeBean empBean;
// Getters and Setters for empBean.


4.6) Repeat Tag

The Tag implements the Basic Iteration Operation and it is generally preferred to Display a Set of Objects found in a Collection. It is very similar to the functionality available in <h:dataTable> Component. Following is usage scenario for this Tag.

<a4j:repeat id = "repeater" value = "#{manager.empList}" var = "employee">
<h:outputText id = "name" value = "#{employee.name}"/>
<h:outputText id = "age" value = "#{employee.age}"/>

Assume that we have a Class called Manager which represents a Collection of Employee objects holding two properties namely name and age. Following is the structure of the Manager Class.


public class Manager{

private List<Employee> employees;
// Getters and setters for employees;



public class Employee{

private String name;
private int age;

// Getters and Setters for name and age


If suppose, we want to display the list of Employees in a Page then we can use the Repeat Tag. The 'value' attribute in the Tag usually represents a Collection and the 'var' attribute can be assumed to hold an element from the Collection object. This tag is identically equivalent to a 'for' loop.

for (Employee employee : manager.getEmployees() ){

4.7) Poll Tag

The Poll Tag is used to Auto Refresh the Current Page by sending Periodic Request to the Server at Regular Intervals by submitting the Form. This can be used in Pages where the View should provide Up-to-Date Information like the Stock Value, Cricket Scores etc. Following is the code snippet demonstrating this Tag.

<a4j:poll id = "refreshId" reRender = "CompId1, CompId2" timeout = "50000"
interval = "1000">

In the above one, the Page will be refreshed automatically after every 1 second (as mentioned in the 'interval' attribute). Note the 'timeout' attribute set to 50 seconds, which means that after 50 seconds the page would stop to Auto Refresh. The List of Components that are to be re-rendered is specified in the 'reRender' attribute.

4.8) Status Tag

The Status Tag can be used as a kind of Indication to the Client about the current Status of the Request, like whether the Request is still being processed by the Server or the Request has been served. Following is the sample code illustrating the same,

<a4j:status startText = "Request sent to the Server" stopText = "Request is completed">

In the above case, whenever the Client initiates a Request then the message 'Request sent to the Server' (as represented by 'startText' attribute) is displayed until the Request is completely processed in which case the message 'Request is Completed' (as represented by 'stopText' attribute) is displayed.

4.9) Support Tag

The mostly commonly used Tag in the Ajax4Jsf Library is the Support which provides Ajax Support to the Jsf Components. It always appears as a Child Tag for the various Jsf Components. Following listing provides the usage of this Tag,

<a4j:inputText id = "userInput">
<a4j:support event = 'onblur' action = "#{bean.process}"
binding = "bean.userInput" reRender = "CompId1, CompId2"/>

In the above sample, whenever the focus is lost for the user input text Field Component, and then the corresponding process method in the Bean class will be invoked. The 'reRender' attribute defines a list of components whose values are to be updates once the request is over. Note the usage of the 'binding' attribute. This attribute resolves to an EL Expressing which maps to the UIInput Control of the Component represented by userInput. Following is the structure in which the Bean class may look like,


public class Bean{

private UIInput userInput;
//Getters and Setters


5) Sample Application

5.1) Introduction

In this section, let us walk through a Sample Application that makes use of the Ajax4Jsf Libraries. Let the keep the functionalities of this Sample Application to a simpler extent. This is a kind of Auto Complete Application in which whenever the User gives the Bank Account Number, the corresponding details like the name of the Bank, its Branch Name, Customer Name, Balance Details, Contact Details etc will be fetched from the Server. The more important thing to note that is the Request that is sent to the Server is not a normal Jsf Request but instead it is a Ajax Request.
5.2) Web Application Descriptor File

As seen previously, the Ajax4Jsf provides a Filter Servlet for adding Ajax capability for the Jsf Components. So, the web.xml should include a 'filter' tag about the various information about the Filter Servlet.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

<display-name>Ajax4jsf Filter</display-name>

<servlet-name>Faces Servlet</servlet-name>

<servlet-name>Faces Servlet</servlet-name>

<servlet-name>Faces Servlet</servlet-name>


<!-- Welcome files -->


As we can see from the above Xml File, apart from the normal Faces Servlet information, a Filter Servlet has been embedded to add Ajax capabilities for the Client Requests.

5.3) Faces Configuration File

The Faces Configuration file (faces-config.xml) contains only one entry that represents a Managed Bean object. As we will see in the later sections, this Managed Bean will contain the logic for creating some Dummy Account Information as well as contains the logic for fetching the appropriate Account Information. Following is the code for faces-config.xml file.


<?xml version="1.0" encoding="UTF-8"?>

<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee"


5.4) Jsp File containing Jsf and Ajax4Jsf Tags

The following Jsp page presents an Interface to the user, when the User is given a Text-Field prompting to enter the Account Information. If the Account Number entered in valid, which is done by comparing the list of Account Objects, then the corresponding related Information of the Account will be populated in the View.


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax" prefix="a4j" %>

Enter the Account number and tab out for getting further information

The main thing to observe in the Jsp Page is for the <a4j:support> tag which is embedded within the <h:inputText> tag representing the Account Number. Since we want support for the Account Number Text-Field we have done like this. That's all, just by adding this support Tag within the Jsf UI Components, automatically Ajax Support will be applicable to the JSF UI Components. The attribute 'event' is set to 'onblur' which means that the corresponding listener method as represented by the 'actionListener' attribute (search() defined inside the AccountSearcher class) will be called when the focus is lost from the Text Field control (which means after tabbing out from the Control). The most significant attribute is the support tag is the 'reRender' attribute which takes a comma separated list of Component Identifiers that want to be re-rendered once the control returns back from the Server.

The 'binding' attribute evaluates to a Jsf EL Expression, if specified will map to the corresponding UI Component in the Backing Bean Class. For example, consider the following code snippet,

<h:inputText id = "AccountNo" binding = "#{accountSearcher.accountTextField}">

The binding expression is given as "#{accountSearcher.accountTextField}, which means that the Input Control directly maps to a property by name accountTextField in the AccountSearcher class which is of type javax.faces.component.UIInput. Following is the Java Code for the same,


public class AccountSearcher {

private UIInput accountTextField;
// Getters and Setters for the same.


5.5) Account.java

Following is the class that encapsulates pieces of information like Account Number, Bank Name, Customer Name, Branch Name, Account Opening Date, Contact Information inside the Account class. Following is the complete Listing for the Account.java class.


package net.javabeat.articles.ajax4jsf.introduction;

import java.util.Date;

public class Account {

private long accountNo;
private String bankName;
private String customerName;
private String branchName;
private String openDate;
private double closingBalance;
private String address;
private String emailId;
private String phoneNumber;

public Account() {

public long getAccountNo() {
return accountNo;

public void setAccountNo(long accountNo) {
this.accountNo = accountNo;

public String getBankName() {
return bankName;

public void setBankName(String bankName) {
this.bankName = bankName;

public String getCustomerName() {
return customerName;

public void setCustomerName(String customerName) {
this.customerName = customerName;

public String getAddress() {
return address;

public void setAddress(String address) {
this.address = address;

public String getEmailId() {
return emailId;

public void setEmailId(String emailId) {
this.emailId = emailId;

public String getBranchName() {
return branchName;

public void setBranchName(String branchName) {
this.branchName = branchName;

public String getOpenDate() {
return openDate;

public void setOpenDate(String openDate) {
this.openDate = openDate;

public double getClosingBalance() {
return closingBalance;

public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;

public String getPhoneNumber() {
return phoneNumber;

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;

5.6) AccountCreator.java

This Utility Class is used to create Dummy Account Information Objects and acts as Storage for those Account Objects. When looked-up for an Account object by giving the Account Number as a Key, the appropriate Object is returned. The Managed Bean references this Class heavily for creating and retrieving Account Objects. Following listing is the complete code for AccountCreator.java


package net.javabeat.articles.ajax4jsf.introduction;

import java.util.HashMap;
import java.util.Map;

public class AccountCreator {

private static Map<Long, Account> accounts;

public static void createTestAccounts(){
if (accounts == null || accounts.isEmpty()){
accounts = new HashMap<Long, Account>();

Account account = null;
account = createAccountInfo(123456, "Hdfc Bank",
"Jenny", "Shastri Nagar, Chennai",
"10/05/2003", 100033.53, "Address1",
"jenny@gmail.com", "99123456789");
accounts.put(account.getAccountNo(), account);

account = createAccountInfo(234567, "Icici Bank",
"Joseph", "Besant Nagar, Chennai",
"121/09/2001", 3200033.53, "Address2",
"joseph@gmail.com", "99987654321");
accounts.put(account.getAccountNo(), account);

private static Account createAccountInfo(long accountNo, String bankName,
String customerName, String branchName, String openDate,
double closingBalance, String address, String emailId, String phoneNumber){

Account account = new Account();
return account;

public static Account getAccountInfo(Long accountNo){
return accounts.get(accountNo);

5.7) Account Searcher.java

This Managed Bean takes care of creating Dummy Account Objects and it returns the appropriate Account Information back to the Client upon Request. Most of the code in this class represents the getters and the setters for the various UI Components in the Jsp Page. The search logic is implemented in the search() method which takes ActionEvent as its only parameter. Following is the code for the same.


package net.javabeat.articles.ajax4jsf.introduction;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

public class AccountSearcher {

private Account account;

private UIInput accountTextField;
private UIInput bankNameTextField;
private UIInput customerNameTextField;
private UIInput branchNameTextField;
private UIInput openDateTextField;
private UIInput closingBalanceTextField;
private UIInput addressTextArea;
private UIInput emailIdTextField;
private UIInput phoneNumberTextField;

public AccountSearcher() {

public void search(ActionEvent actionEvent){

String strAccountNo = (String)getAccountTextField().getSubmittedValue();
long accountNo = 0L;
accountNo = Long.parseLong(strAccountNo);
account = AccountCreator.getAccountInfo(accountNo);
if (account != null){
// Error Message.
}catch(Exception exception){

private void setComponentsValueToNull(){

public Account getAccount() {
return account;

public void setAccount(Account account) {
this.account = account;

public UIInput getAccountTextField() {
return accountTextField;

public void setAccountTextField(UIInput accountTextField) {
this.accountTextField = accountTextField;

public UIInput getBankNameTextField() {
return bankNameTextField;

public void setBankNameTextField(UIInput bankNameTextField) {
this.bankNameTextField = bankNameTextField;

public UIInput getCustomerNameTextField() {
return customerNameTextField;

public void setCustomerNameTextField(UIInput customerNameTextField) {
this.customerNameTextField = customerNameTextField;

public UIInput getBranchNameTextField() {
return branchNameTextField;

public void setBranchNameTextField(UIInput branchNameTextField) {
this.branchNameTextField = branchNameTextField;

public UIInput getOpenDateTextField() {
return openDateTextField;

public void setOpenDateTextField(UIInput openDateTextField) {
this.openDateTextField = openDateTextField;

public UIInput getClosingBalanceTextField() {
return closingBalanceTextField;

public void setClosingBalanceTextField(UIInput closingBalanceTextField) {
this.closingBalanceTextField = closingBalanceTextField;

public UIInput getAddressTextArea() {
return addressTextArea;

public void setAddressTextArea(UIInput addressTextArea) {
this.addressTextArea = addressTextArea;

public UIInput getEmailIdTextField() {
return emailIdTextField;

public void setEmailIdTextField(UIInput emailIdTextField) {
this.emailIdTextField = emailIdTextField;

public UIInput getPhoneNumberTextField() {
return phoneNumberTextField;

public void setPhoneNumberTextField(UIInput phoneNumberTextField) {
this.phoneNumberTextField = phoneNumberTextField;

Take a careful look at the implementation of the Search Logic. After getting the submitted value of the Account Text Field by calling UIInput. getSubmittedValue(), the code tries to perform a lookup operation in the Account Storage. If an Account object is obtained, then the code explicitly sets all the submitted information of the UI Components to Null. This is necessary because by setting all the Submitted Value of the Input Components to null, we are ensuring that the Component's Value will be taken from the appropriate Model Objects.

6) Conclusion

Many of the Vendors have started using Ajax4Jsf Framework in their Web Applications due to its simplicity. No need to depend on JavaScript code to make use of Ajax Functionality. This article initially focused on explaining the need to have another Framework for the Web Tier. Then it provided a Brief Information about the Workflow that happens in an Ajax4Jsf enabled Web Application. Then the most commonly used Ajax4Jsf Tags are explained in detail. Finally the article concluded by giving a Sample AutoComplete Application for populating the User Account Information when given the Account Number.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}