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.:
# | Attribute | Description |
---|---|---|
1. | disabled | If true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled. |
2. | event | The event that will invoke Ajax requests, for example, click, change, blur, keypress etc. |
3. | execute | Attribute 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. | immediate | If true, behavior events generated are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase. |
5. | listener | An EL expression for a method in a backing bean called during the Ajax request. |
6. | onerror | The name of a JavaScript callback function in case of an error during the Ajax request. |
7. | onevent | The name of a JavaScript callback function to handle UI events. |
8. | render | Attribute 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!
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
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)
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
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
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
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)
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)
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
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" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < 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
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
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> < html lang = "en" xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" > < h:head > < meta charset = "utf-8" name = "viewport" content = "width=device-width, initial-scale=1" http-equiv = "X-UA-Conpatible" /> < link type = "text/css" rel = "stylesheet" href = "https://examples.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css" /> < 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
A new pop window will open where we will enter the package name as 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
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
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
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.
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.
Enter the name and press the Say Hello button. You will see the following result without the page refresh.
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
You can download the full source code of this example here: JSF Ajaxrender