Basic AJAX in JSF

In this article I would like to describe how to send AJAX request to server, receive the response and update the page accordingly. As an example I will use a simple application which allows choosing country from a list. Once the country is chosen, the list of cities is automatically updated. The main screen of the application will look like this:

The good thing about AJAX in JSF is that all the work related to generating request, sending request, receiving response and processing it is hidden behind well-defined abstractions. Actually, it is often enough to specify the event which triggers the request, which parts of the page needs to be sent to server and which parts of the page needs to be updated after receiving response.

Optionally, error handlers and listeners may be specified apart from other things. Additionally, JSF performs the queueing of AJAX requests to ensure that next request is started after the previous one finishes.

Managed bean

Below is the managed bean used by the application. What is important here is that the bean has no knowledge that AJAX will be used.

package com.example.ajaxcities;

import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Named;

public class Cities implements Serializable {
    private static final long serialVersionUID = 2347238972389L;
    private static final Logger LOGGER = Logger.getLogger(Cities.class.getName());

    private CityDAO cityDAO;
    private SelectItem[] countrySelectItems;
    private String country;
    private SelectItem[] citySelectItems;
    private String city;

    public void init() {
    public String getCountry() {
        return country;

    public void setCountry(String country) { = country;
        createCitySelectItems();"Selected country: %s", country));

    public SelectItem[] getCountries() {
        return countrySelectItems;
    private void createCountrySelectItems() {
        String[] countries = cityDAO.getAllCountries();
        if (countries != null && countries.length > 0) {
            country = countries[0];
            countrySelectItems = new SelectItem[countries.length];
            for (int i = 0; i < countries.length; i++)
                countrySelectItems[i] = new SelectItem(countries[i], countries[i]);
        } else {
            country = "";
            countrySelectItems = new SelectItem[0];
    public String getCity() {
        return city;
    public void setCity(String city) { = city;

    private void createCitySelectItems() {
        String[] cities = cityDAO.getCities(country);
        if (cities != null && cities.length > 0) {
            city = cities[0];
            citySelectItems = new SelectItem[cities.length];
            for (int i = 0; i < cities.length; i++) {
      "Adding to cities: %s", cities[i]));
                citySelectItems[i] = new SelectItem(cities[i], cities[i]);
        } else {
            city = "";
            citySelectItems = new SelectItem[0];
    public SelectItem[] getCities() {
        return citySelectItems;

The actual place where we use AJAX is the XHTML web page. It can be done in two ways.

Declarative AJAX

The first method is to put <f:ajax> tag inside XHTML element which triggers the AJAX request. It is very convenient because we don’t need to write any JavaScript code.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns=""
            <h:panelGrid columns="2">
                <h:selectOneMenu id="countryList" value="#{}">
                    <f:selectItems value="#{cities.countries}" />
                    <f:ajax event="change" execute="countryList" render="cityList" />
                <h:selectOneMenu id="cityList" value="#{}">
                    <f:selectItems value="#{cities.cities}" />
            <h:commandLink action="index" value="#{msgs.back}" />

The element

<f:ajax event="change" execute="countryList" render="cityList" />

informs JSF engine that once the JavaScript event specified in event attribute will occur, the components specified in execute attribute will be executed on server and the components specified in render attribute will be rendered (updated on the web page).

The possible values of event attribute are the same as in JavaScript but without on prefix. In our case the AJAX request will be sent every time the country is changed.

Attribute execute contains space-separated list of HTML identifiers of the elements that will be executed on server. In our case element with identifier countryList will be executed which means that its value will be set in bean. Attribute execute may also contain four special values: @this, @form, @all and @none. If execute attribute is not specified, default value of @this will be used.

Attribute render contains space-separated list of HTML identifiers of the elements that will be updated on the web page once the AJAX response is received. It also supports four special values as execute attribute but the default value is @none.

AJAX using JavaScript library

Tag <f:ajax> is very convenient but it also has some limitations which may be an issue in more advanced cases. Luckily, it is also possible to directly use JavaScript library to send AJAX requests to server.

First the library must be referenced from the web page using construction:

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

Once it is done we can execute AJAX request using JavaScript when an event happens:

<h:selectOneMenu id="countryList" value="#{}"
      onchange="jsf.ajax.request(this, event, {
                  execute: 'main:countryList',
                  render: 'main:cityList' });">
      <f:selectItems value="#{cities.countries}" />

Actually, this does not seem much different from using <f:ajax> tag but it gives us more control over what is being sent. For example it allows us to pass additional parameters in AJAX request apart from execute and render and then process them on the server.


AJAX is becoming more and more popular because it gives faster and smoother user experience without constantly reloading the web page. This makes it a great alternative to using value change listeners. I hope you will find it useful in your own projects.

All the code for this example was tested on Glassfish and is available at Github

About Robert Piasecki

Husband, software developer, Linux and open-source fan, blogger.
This entry was posted in AJAX, Java, Java EE, JSF and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Basic AJAX in JSF

  1. Hi, the whole thing is going nicely here and ofcourse every one is sharing information,
    that’s really excellent, keep up writing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s