skip to main | skip to sidebar

Sunday, June 27, 2010

Simple AJAX [, JSP] Example

You will find many examples to learn how AJAX [Asynchronous Java Script And XML] works, but this one is different. Its one of the best way of using AJAX in web applications. The difference -  many of the examples you find uses Java Script to parse the AJAX response, this example avoids that parsing Java Script and uses JSP to generate the HTML and uses simple Java Script just to make the asynchronous call and show the response. It shows simple way of using JSP and AJAX with as much less Java Script as possible. This article wont go into details of what AJAX is and how to make AJAX calls, it explains one good way among many to use AJAX. Lets get on with it then!
The flow of this example is like this – A simple JSP page where user performs an action [button click in this example] to get list of employees, on this action we’ll make an Asynchronous call to a Servlet which will prepare the dummy employee data and sends that data to a JSP page. This JSP generates the HTML displaying the employee data in a tabular format. The Java Script which made the asynchronous call will receive this HTML and just inserts into the one of the HTML element in the page. That is it. All the Java Script we’ve is just to make an asynchronous call, receive the response HTML and insert into the current page. You can download the complete source code using the links given at the end of this post. The compressed file is an eclipse project, you can directly create eclipse project from the extracted directory.
Didn’t get the clear picture of it yet? do not worry lets go through code which makes it easier for you to understand. First we’ll see the server side code which prepares the data. In this example I tried to separate the layers clearly so that you can replace this layer where we prepare dummy data with actual database code which prepares data by querying database. The DTO object we are going to use to hold each employee information is “EmployeeDTO”, its code is as follows.
public class EmployeeDTO {
    private int empId;
    private String name, email;
    private String designation, department; 
    public EmployeeDTO(int empId) {         this.empId = empId;     }
    public int getEmpId() {         return empId;     }
    public void setEmpId(int empId) {         this.empId = empId;     }
    public String getName() {         return name;     }
    public void setName(String name) {         this.name = name;     }
    public String getEmail() {         return email;     }
    public void setEmail(String email) {         this.email = email;     }
    public String getDesignation() {         return designation;     }
    public void setDesignation(String designation) {         this.designation = designation;     }
    public String getDepartment() {         return department;     }
    public void setDepartment(String department) {         this.department = department;     } }
EmployeeDTO is just a class with few fields to hold employee details and getter/setter method for all the fields. The DAO, which prepares dummy data is as follows
import java.util.ArrayList;
import java.util.List; 
import com.rakesh.ex.dto.EmployeeDTO;

public class EmployeeDAO {
    /**      * sample method to get list of employees. This method creates sample list      * of employees data.      */     public List<EmployeeDTO> getEmployees() {         List<EmployeeDTO> empList = new ArrayList<EmployeeDTO>();         for (int i=1; i<=10; i++)             empList.add(createSampleData(i, i%2));         return empList;     }
    private static EmployeeDTO createSampleData(int i, int j) {         EmployeeDTO emp = new EmployeeDTO(1000 + i);         emp.setName("Employee" + i);         emp.setEmail(emp.getName() + "@company.com");         emp.setDesignation("Designation" + i);         emp.setDepartment("Department" + j);         return emp;     } }
There’s nothing much in the above code – it has two methods, one public and the other private static method. The private static method, just prepares dummy employee information. The public method ‘getEmployees()’ creates an ArrayList of EmployeeDTO objects with dummy employee information and returns it. It loops for 10 times and calls the private static method ‘createSampleData()’ each time. You might want to replace the code in this DAO with actual code which queries database to get the employee information.
Now the servlet which gets called asynchronously from Java Script, its code is as follows
import java.io.IOException;
import java.util.List; 
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.rakesh.ex.dao.EmployeeDAO; import com.rakesh.ex.dto.EmployeeDTO;

public class AjaxExample extends HttpServlet {     private static final long serialVersionUID = -6377586508833712244L;
    private EmployeeDAO empDAO;
    @Override     public void destroy() {         super.destroy();         this.empDAO = null;     }
    @Override     public void init() throws ServletException {         super.init();         this.empDAO = new EmployeeDAO();     }
    @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         // get employee list         List<EmployeeDTO> empList = empDAO.getEmployees();         // set employee list in to request         req.setAttribute("emp_list", empList);
        // forward to jsp which generates table out of employee list         req.getRequestDispatcher("emp_list.jsp").forward(req, resp);         return;     }
}
This “AjaxExample” servlet extends “HttpServlet” and overrides “init()”, “destroy()”, and “doGet()” methods. We’ll instantiate DAO object in the “init()” method and remove the reference in “destroy()” method. The “doGet()” method uses this DAO object and calls “getEmployees()” method to get employees data. This method returns a list of EmployeeDTO objects. We’ll set this “List” object as request attribute and forward to “emp_list.jsp” page. That is all we do in this servlet. Simple isn’t it? lets see the “emp_list.jsp”.
<%@page import="java.util.List" %>
<%@page import="com.rakesh.ex.dto.EmployeeDTO" %>
<%
    List<EmployeeDTO> empList = (List<EmployeeDTO>)request.getAttribute("emp_list");
    if (empList == null || empList.isEmpty()) {
%>
    <p>Employee list is empty!</p>
<% } else { %>
    <table width="100%" border="1">
        <tr><th colspan="5" align="center"><h3>Employee Info</h3></th></tr>
        <tr>
            <th>Emp-Id</th><th>Name</th><th>Email</th><th>Designation</th><th>Department</th>
        </tr>
        <% for (EmployeeDTO emp : empList) { %>
            <tr>
                <td><%=emp.getEmpId()%></td>
                <td><%=emp.getName()%></td>
                <td><%=emp.getEmail()%></td>
                <td><%=emp.getDesignation()%></td>
                <td><%=emp.getDepartment()%></td>
            </tr>
        <% } %>
    </table>
<% } %>
This JSP generates a ‘HTML table’ with the details of employees. Important thing to observe is, this JSP doesn’t generate complete HTML [I mean HTML, BODY, etc tags], it only generates the ‘table’. It gets the ‘List’ object from request and loops through it and adds ‘<tr>’ tag for each ‘EmployeeDTO’. Even this code block is not complex, plain simple JSP code.
Now the core of this post, the Java Script which makes the asynchronous call.
AjaxEx = function(url, elId) {
    if (!url || !elId) {
        alert("Invalid input!");
        return;
    }
    var el = document.getElementById(elId);
    if (!el) {
        alert("Container Element, to place Ajax response doesn't exists!");
        return;
    }
    this.init(url, el);
}; 
AjaxEx.prototype = {     init : function (url, el) {         this.el = el;         this.url = url;
        this.sampleHtml = "<p>This will be replaced with AJAX response!</p>";
        // create xml http request object for AJAX requests         this.xmlHttp = this.initXmlHttp();
    },
    initXmlHttp : function () {         if (window.XMLHttpRequest)             // Firefox, Opera, IE7, etc.             return new XMLHttpRequest();         if (window.ActiveXObject)             // IE6, IE5             return new ActiveXObject("Microsoft.XMLHTTP");     },
    resetContent : function () {         this.el.innerHTML = this.sampleHtml;     },
    sendAjaxRequest : function () {         // initialize XML Http object if not available         if (!this.xmlHttp)             this.xmlHttp = this.initXmlHttp();
        if (this.xmlHttp) {             var ajaxObj = this;             this.xmlHttp.onreadystatechange = function() {                 if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) {                     // 4 = "loaded", 200 = "OK"                     ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText;                 }             };             this.xmlHttp.open("GET", this.url, true);             this.xmlHttp.send(null);         } else             alert("Your browser does not support AJAX.");     } };
function makeAjaxCall(ajaxObj, flag) {     if (flag) {         ajaxObj.sendAjaxRequest();         return;     }     ajaxObj.resetContent(); }
Above Java Script code might look big, but its really simple. We have a “AjaxEx” class with few methods in it, and a Java Script method “makeAjaxCall()”. First lets see what ‘makeAjaxCall()’ does. It takes two parameters – one ‘ajaxObj’ - the AjaxEx instance and the other ‘flag’ – true/false to decide whether to make Ajax call and update content OR reset the previously displayed content with default text. This ‘makeAjaxCall()’ method checks the ‘flag’ parameter value - if its true, it calls  ‘sendAjaxRequest()’ method on ‘ajaxObj’ object and returns, else calls ‘resetContent()’ on ‘ajaxObj’ object.
“AjaxEx” class has four methods in it – ‘init()’, ‘initXmlHttp()’, ‘resetContent()’, and ‘sendAjaxRequest()’. To instantiate ‘AjaxEx’ class you need to pass two values to it – one ‘url’ which is the servlet URL to which we need to make asynchronous requests for employee information, second ‘elId’ – the id attribute of the HTML element in which we need to place the response. When you create instance of ‘AjaxEx’, it validates these two inputs and then calls ‘init()’ method.
The ‘init()’ method sets references to the servlet URL and the DOM reference to the HTML element in which we need to place AJAX response. Then it calls ‘initXmlHttp()’ method. This method does nothing but creating XML Http Request object according to the browser you are using. For IE5 and IE6 it creates instance of ‘ActiveXObject’ and ‘XMLHttpReques’ object for other browsers. The third method in ‘AjaxEx’ is ‘resetContent()’ method, this is very simple one, its just resets the content of the DOM Html element [the one with the ID, which is passed as second parameter to AjaxEx(…)] with default text. Well now the important part of this file – the ‘sendAjaxRequest()’ method.
This method first checks whether the XML Http object is created or not. If not then it calls ‘initXmlHttp()’ method to create it. After this we’ll initialize what to do when we receive the response. The line where we set reference to “xmlHttp.onreadstatechange’ – we created an inline function and in it we check the response status – if the readState is ‘4’ and status is ‘200’ which says we’ve got a valid response, and then we’ll just replace the content of the DOM element in which we need to place the response we got for this request. Rest of the two lines where we call ‘open()’ and ‘send()’ are the method calls where we actually make an asynchronous call. That is it about the Java Script we’ve. Now the last part the JSP which will have the button to make the AJAX call.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>     <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Simple Ajax Example</title>
    <script type="text/javascript" src="js/ajax-example.js"></script>     <style type="text/css">         body {             width: 800px;             height: 600px;         }         .top_block {             text-align: center;         }         .top_block input {             font-weight: bold;         }         .ajax_content {             border: 2px solid #000;             padding: 2em;         }     </style> </head> <body>     <div class="top_block">         <input type="button" onclick="javascript:makeAjaxCall(ajaxObj, true);"
                value="Get Data"/>&nbsp;&nbsp;         <input type="button" onclick="javascript:makeAjaxCall(ajaxObj, false);"
                value="Reset Content"/>     </div>     <div id="ajax_content" class="ajax_content">         <p>This will be replaced with AJAX response!</p>     </div>     <script type="text/javascript">     <!--         // view source of this page after it loads in browser         // and check this variables value         var url = "<%=request.getContextPath()%>/ajaxServlet";         var ajaxObj = new AjaxEx(url, "ajax_content");     // -->     </script> </body> </html>
This is a simple JSP, with three parts to observe. One the “ajax-example.js” file import in the ‘head’ tag, second the ‘onclick’ events for the two input tags in first div element, and the ‘script’ block at the end of the page just before the closing ‘body’ tag. What are we doing in this page – this page uses two div elements, the top one shows two buttons - ‘Get Data’ and ‘Reset Content’. Both the buttons call ‘makeAjaxCall()’ method when clicked, but with a difference in the second parameter. ‘Get Data’ button passes ‘true’ to make the AJAX call and ‘Reset Content’ passes ‘false’ to reset the content.
And the Java Script block at the end has code to create object for ‘AjaxEx’ Java Script class. The URL Java Script variable is set to the ‘AjaxExampleServlet’ and then we’ll create AjaxEx object using the ‘new’ keyword, and pass the URL and the id ‘ajax_content’ to it. If you observe the HTML in the body you’ll find the second div element has this id value ‘ajax_content’ assigned to it. Well that is it, isn’t it simple! What I tried here is to show the simple and a good way of using AJAX with less usage of Java Script.
Please download the source code used in this example using the link give below.
Download the source code.
The download file is a .rar file, which already have eclipse project files, you might have to update the eclipse class path and update servlet-api.jar. It also has ANT build script to generate the .war file for deployment. I used Tomcat path to have servlet-api.jar file in class path to compile the project, you need to update this path with your local one. Hope this helps to download and start right away :)

5 comments:

tirupatiprasadam said...

thanks for nice post.. From a very long time i was thinking to know about AJAX... NOW i got the knowledge of the AJAX.... KEEP POSTING...

ritu said...

how to pass a selected value from a list to Ajax as a parameter and display the result in the jsp..!

Anyhelp is appreciated..............

Rakesh Reddy said...

Here you go
http://iam-rakesh.blogspot.com/2010/09/ajax-form-submit-getpost-methods.html

Sorry for the delayed reply!

ping said...

Hi Rakesh, how to do AJAX script like this, but using combo box insted of button?
Example I have combo box with status values: unread, read, deleted (messages). When I choose one of combo box values, table will be show all messages with choosen status.
best regards,
Kajbum

Rakesh Reddy said...

Hi, Sorry for the delayed reply, holiday came a bit early for me ;)
In the example above I used a button and 'onclick' event to make an asynchronous request, for your requirement you use 'onchange' event of your select box, something like this
<select onchange="javascript:makeAjaxCall(ajaxObj, true);" ...>
....
</select>

Post a Comment