Java Server Faces: AJAX

Since, AJAX is an extremely powerful technology, JSF provides the tag <f:ajax> to support AJAX capabilities in a standard way. Note that Ajax allows web pages to communicate with the web server asynchronously and can refresh a part of the web page. This is implemented with its execute and render attributes. The execute attribute holds space-separated ids of the components whose values have to be sent to the server. The result of the AJAX request is placed in a component whose id is specified in the render attribute. Here is an example(AjaxTest.xhtmi):

<html xmlns=””





<h:inputText id=”in” value=”#{expander.shortName}”/>=

<h:outputText id=”out” value=”#{expander.longName}”/><br/>

<h:commandButton value=”Get full form”>

<f:ajax execute=ninn render=”out”/>





This page contains three components: a text box, a label and a button. Users type an abbreviated form such as JSF, JSP etc in the text box. The <f:ajax> tag within opening and closing <h:commandButton> tags makes the button Ajaxable. This means, when the button is clicked, an AJAX request is sent to the server instead of submitting the whole form. The value of the text box having id attribute value in is sent to the server. Upon response, the result (expanded form) is placed in the component having the id out. The managed bean that performs the expansion is shown below:

package ajax;

import javax.faces.bean.*;

@ManagedBean(name=”expander”, eager=true)

@ApplicationScoped public class Expander {

java.util.Hashtable db = new java.util.Hashtable();

String sn=”JSP”; public Expander() {

db.put(“JSF”, “Java Server Faces”);

db.put(“JSP”, “Java Server Pages”);


public String getShortName() { return sn; }

public void setShortName(String sn) { = sn; }

public String getLongName() {

Object o = db.get(sn);

return o != null? (String)o : “Not found”;



The values of multiple components have to be sent to the server, specify their ids in the execute attribute. The result can be placed in multiple components in the same way:

<h:form id=”fi”>

<h:inputText id=”txt1″ value=”#{aBean.property1}”/>

<h:outputText id=”out1″ value=”#{aBean.property4}”/>



<h:inputText id=”txt1″ value=”#{aBean.property2}”/>

<h:inputText id=”txt2″ value=”#{aBean.property3}”/>

<h:outputText id=”out1″ value=”#{aBean.property4}”/><br/>

<h:commandButton value=”Submit”>

<f:ajax execute=”txt1 txt2 f1:txt1” render=”out1 f1:out1″/> </h:commandButton>


To send values of every component in the parent form, use

<f:ajax execute=”@form” render=”out”/>

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *