jsf

JSF Ajax Render Example

Hello, in this tutorial I would like to describe how to send AJAX request to the server, receive the response and update the page accordingly and will demonstrate the following:

  • Ajax enabled input form
  • Sending & receiving data to & from a managed bean
  • Output page to display the result

This example will show the implementation of ajax in jsf.
 
 
 

1. Introduction

AJAX is an acronym for Asynchronous JavaScript and XML. It is a technique to use HTTPXMLObject of JavaScript to send data to the server and receive data from the server asynchronously (i.e. without reloading the whole page). Thus, making the application interactive and faster.

The good thing about AJAX in JSF is that all the work related to generating a request, sending a request, receiving a response and processing it, is hidden behind well-defined abstractions.

In the below tutorial, we will have the following components:

  • ajax.xhtml – A jsf page having the Ajax component to accept user input and display the output
  • HelloBean.java – A managed bean class which holds a message to be displayed on the page
  • web.xml – Web application configuration file

This sample application will support the ajax call with <f:ajax /> tag in jsf.

1.1 How it can be achieved?

Programmers need to implement the <f:ajax> tag in a jsf application to handle the ajax calls. Let’s take a look at the tag and understand how it is done:

JSF Ajax Tag

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

The element <f:ajax> informs JSF engine that once the event will occur, the component specified in execute attribute will be executed on the server and the component specified in render attribute will be rendered on the webpage once the ajax response is received.

1.2 Tag Attributes

There are multiple attributes that can be used with the ajax tag, for e.g.:

#AttributeDescription
1.disabledIf true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled.
2.eventThe event that will invoke Ajax requests, for example, click, change, blur, keypress etc.
3.executeAttribute execute contains a space-separated list of HTML identifiers of the elements that will be executed on the server. In our example, the element with identifier nameId will be executed which means that its value will be set in the bean. The attribute execute may also contain four special values: @this, @form, @all and @none. If execute attribute is not specified, the default value of @this will be used.
4.immediateIf true, behavior events generated are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase.
5.listenerAn EL expression for a method in a backing bean called during the Ajax request.
6.onerrorThe name of a JavaScript callback function in case of an error during the Ajax request.
7.oneventThe name of a JavaScript callback function to handle UI events.
8.renderAttribute render contains a 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.

Now, open up the Eclipse IDE and let’s start building the application!

2. JSF Ajax Render Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 (1.8.0_131), Tomcat7 application server and MySQL database. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

JSF Ajax Render -  Application Project Structure
Fig. 1: Jsf Ajax Render Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Dynamic Web Java project with Eclipse. In Eclipse IDE, go to File -> New -> Dynamic web project

JSF Ajax Render - Web Project
Fig. 2: Create Dynamic Web Project

In the New Dynamic Project window fill in the below details and click next

  • Enter the project name and project location
  • Select Target runtime as Apache Tomcat v7.0 from dropdown
  • Select Configuration as JavaServer Faces v.2.2 Project from dropdown (this is required to download the java server faces capabilities in your project)

Fig. 3: Project Details
Fig. 3: Project Details

Leave everything as default in this window as we will be making the required java file at a later stage. Simply click next and we will land up on the web-module window

Fig. 4: Java Src Window
Fig. 4: Java Src Window

In the Web Module window, leave the context_root and content_directory values as default (however, you can change the context_root but for the first application let’s keep it as a default value). Simply, check Generate web.xml deployment descriptor checkbox and click next

Fig. 5: Web Module Window
Fig. 5: Web Module Window

In the JSF Capabilities windows, we will require downloading the dependencies (not available by default) so that our project is configured as a JSF module in Eclipse. Add the JSF capabilities to the web project by clicking on the download icon (encircled in Fig. 6) and download the JSF 2.2 Mojarra implementation

Fig. 6: JSF Capabilities Window
Fig. 6: JSF Capabilities Window

A new pop-up window will open where it will auto lists down the JSF library. Select the JSF 2.2 library and click next (the library name and download destination will be auto populated)

Fig. 7: JSF Capabilities Download Window
Fig. 7: JSF Capabilities Download Window

Check the license checkbox and click finish. Eclipse will download the JSF 2.2 library and will display them on the JSF capabilities windows (i.e. Fig. 6)

Fig. 8: JSF Capabilities License Window
Fig. 8: JSF Capabilities License Window

Now the JSF implementation libraries will be listed down on the capabilities page. Select the checkbox (JSF2.2 (Mojarra 2.2.0)) and leave everything else as default. Click Finish

JSF Ajax Render - Library Selection Window
Fig. 9: JSF Capabilities Library Selection Window

Eclipse will create the project named JSF Ajaxrender in the workspace and web.xml will be configured for accepting the JSF requests. It will have the following code:

web.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="UTF-8"?>
    <display-name>JSF Ajaxrender</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>resources.application</param-value>
    </context-param>
    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
</web-app>

Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application:

3.1 Source File Creation

For the demo, we are using a simple form application. Right click on project WebContent -> New -> File

Note: In JSF 2.0, it’s recommended to create a JSF page in xhtml format, a file format with .xhtml extension

Fig. 10: File Creation
Fig. 10: File Creation

A pop-up window will open. Verify the parent folder location as JSF Ajaxrender/WebContent and enter the file name as ajax.xhtml. Click Finish

Fig. 11: ajax.xhtml
Fig. 11: ajax.xhtml

3.1.1 Implementation of Source file

Here in the ajax.xhtml, we will 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.

Tip

  • The execute attribute of the <f:ajax /> element indicates that only the elements specified here are submitted to the server. In our case, only nameId will be submitted to the server for processing.
  • The render attribute of the <f:ajax /> element will refresh the component with an id of messageId if the ajax request is finished.

Add the following code to it:

ajax.xhtml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE HTML>
<h:head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" http-equiv="X-UA-Conpatible" />
    <title>JSF Ajax Render</title>
    <style type="text/css">
        #ajaxForm {
            margin: 18px;
        }
        .nameTextbox {
            margin-left: 12px;
        }
        #btn {
            padding: 12px 0px 0px 0px;
        }
        #output {
            padding-top: 12px;
            color: green;
        }
    </style>
</h:head>
<h:body>
    <center><h2>JSF Ajax Render Example</h2></center>
    <h:form id="ajaxForm">      
        <div id="input">
             <h:outputLabel value="Enter Name:" /><h:inputText id="nameId" styleClass="nameTextbox" value="#{helloBean.name}" />
        </div>
        <div id="btn">
            <h:commandButton value="Say Hello" styleClass="btn btn-primary btn-sm">
                <f:ajax execute= "nameId" render="messageId" />
            </h:commandButton>
        </div>
        <div id="output">
            <h4><h:outputText id="messageId" value="#{helloBean.message}" /></h4>
        </div>
    </h:form>
</h:body>
</html>

3.2 Java Class Creation

Let’s create the required java files. Right click on src folder New -> Package

Fig. 12: Java Package Creation
Fig. 12: Java Package Creation

A new pop window will open where we will enter the package name as com.ajaxrender.example

Fig. 13: Java Package Name (com.ajaxrender.example)
Fig. 13: Java Package Name (com.ajaxrender.example)

Once the package is created in the application, we will need to create the required managed bean. Right click on the newly create package New -> Class

Fig. 14: Java Class Creation
Fig. 14: Java Class Creation

A new pop window will open and enter the file name as HelloBean. The managed bean class will be created inside the package com.ajaxrender.example

Fig. 15: Java Class (HelloBean.java)
Fig. 15: Java Class (HelloBean.java)

3.2.1 Implementation of Managed Bean Class

Below is the managed bean which is used by the application. What is important here is that the bean has no knowledge that AJAX will be used. Add the following code to it:

HelloBean.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.ajaxrender.example;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean @SessionScoped
public class HelloBean {
    public String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMessage() {
        String response = "";
        if(name != null) {
            response = "Ajax Message: Hello, " + name +"!";
        }
        return response;
    }
}

4. Project Deploy

Once we are ready with all the changes done, let us compile and deploy the application on tomcat7 server. In order to deploy the application on tomcat7, right-click on the project and navigate to Run as -> Run on Server

Fig. 16: How to Deploy Application on Tomcat
Fig. 16: How to Deploy Application on Tomcat

Tomcat will deploy the application in its webapps folder and shall start it’s execution to deploy the project so that we can go ahead and test it on the browser.

Fig. 17: Tomcat Processing
Fig. 17: Tomcat Processing

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JSFAjaxrender/faces/ajax.xhtml

Server name (localhost) and port (8085) may vary as per your tomcat configuration

5. Project Demo

Now, we are done with the application creation and it’s time to test out the application. Accessing the page: ajax.xhtml, we will see sample form page.

Fig. 18: Ajax Enabled Form Page
Fig. 18: Ajax Enabled Form Page

Enter the name and press the Say Hello button. You will see the following result without the page refresh.

Fig. 19: Result Page
Fig. 19: Result Page

Hope this helped :)

6. Conclusion

Through this example, we learned about the Ajax implementation in jsf. All the code for this example was deployed using the Tomcat7 application server.

7. Download the Eclipse Project

This was a JSF Ajax Render example with Eclipse and Tomcat

Download
You can download the full source code of this example here: JSF Ajaxrender

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button