AJAX Example using Servlet and JAVA

Ajax(Asynchronous Javascript And XML) is a technique we can use in web development for creating a faster update to the user interface and better user experience. Ajax makes use of the XMLHttpRequest object to communicate with servers. Using ajax, the user can post data to the backend server without submitting the page or reloading the browser page. Creating an AJAX example application with a servlet is very simple.

In this post, we will learn how to use the Ajax technique to invoke backend servlet, get the response from the servlet and modify the user interface accordingly.

We will learn by creating a simple javascript ajax example.

Versions Details:

  • Eclipse Helios
  • Apache Tomcat v8.
  • json-20140107.jar

Creating AJAX example with servlet application

We will use the Servlet for the backend that handles the requests made through Ajax call and sends JSON responses back to the browser.

Create a dynamic web project on Eclipse IDE. We are creating a Dynamic Web project called AjaxExample, as shown below.

ajax_project

Create a servlet class

In the previous step, we created the dynamic web project. Create a servlet class AjaxHandler.java under the src folder.

This Servlet class handles the Ajax call from our frontend html page. In this class, we are using hardcoded JSON object values as responses. Servlet class returns a JSON array as response upon invoking through Ajax call.

Note that to create JSON objects, we need to add a dependency jar to the classpath or lib of our dynamic web project. In this example, we are using the org.json dependency jar. Download the latest jar and add it to the classpath or put it under WEB-INF/ lib directory.

In the code below, We have implemented the HTTP GET method. 

We are creating a JSON array and adding two JSON objects to the array. Finally, we are returning this JSON array to through response. 

Our JSON object contains name and age attributes. Also, note that the response MIME type is set to application/json as we are returning JSON data.

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet("/AjaxHandler")
public class AjaxHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public AjaxHandler() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        JSONArray array = new JSONArray();
        
        JSONObject user1 = new JSONObject();
        user1.put("name", "TOM");
        user1.put("age", "26");
        JSONObject user2 = new JSONObject();
        user2.put("name", "ASB");
        user2.put("age", "26");
        
        array.put(user1);
        array.put(user2);
        
        response.setContentType("application/json");
        response.getWriter().write(array.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Invoke the servlet using Ajax from html page

In the previous step, we created our backend servlet. Now the final step is to create an html page and add Ajax call into it.

Create an html page index.html under the Webcontent folder of our dynamic web project. Add the following html content to the page. 

We are calling backend servlet using the http GET method(using the XMLHttpRequest) and appending the content returned from servlet on the div html element with the id contentDiv.

<!DOCTYPE html>
< html>
< head>
< style>
#contentTable, th, td{
border : solid 1px black;
}
< /style>
< /head>
< body>
< h2>Ajax Example with Servlet</h2>

< button onclick="callAjax();">Get Data</button>
< br/>< br/>


< table id="contentTable">
< tr>
< th>Name</th>< th>Age</th>
</tr> 
< /table>
< div id="loading"></div>

< script type="text/javascript">
function callAjax() {

document.getElementById('loading').innerHTML = "Loading Data...";

httpRequest = new XMLHttpRequest();

if (!httpRequest) {
console.log('Unable to create XMLHTTP instance');
return false;
}
httpRequest.open('GET', 'AjaxHandler');
httpRequest.responseType = 'json';
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {

document.getElementById('loading').innerHTML = "";

if (httpRequest.status === 200) {

var array = httpRequest.response;
for (var i=0; i< array.length; i++) {

var table = document.getElementById('contentTable');
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var name = document.createTextNode(array[i].name);
var age = document.createTextNode(array[i].age);
cell1.appendChild(name);
cell2.appendChild(age);
}
} else {
console.log('Something went wrong..!!');
}
}
}
}
</ script>
</ body>
</ html>

Brief Explanation:

We have used httpRequest.open(), which opens HTTP connection for us. The first parameter(“GET” in our case) tells which HTTP request method we are going to use. Then we pass the URL of the server with the second parameter.

We can also pass a third optional parameter (with value: true or false), which notifies that whether our request is Asynchronous or not. The default value of this parameter is true.

Next, we have used the httpRequest.send() method, which sends our request to the server. We can also send any data by passing parameters to this method when we use a POST request. The data should be in the format, which the backend server can handle.

If we are POSTing the data, then we may have to set the request header with requests content-type as shown in the example below.

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

AJAX responds with ready state value as XMLHttpRequest.DONE (or value corresponding to 4) once the caller completely receives the response message from the server.

The list of ready state values are:

  • 0 – Indicates request is not initialized.
  • 1 – Server connection is established (or loading).
  • 2 – request is received (or loaded).
  • 3 – request is processing (or interactive).
  • 4 – request is completed and response has been received (or complete ).

Once the response is ready, and the server responds successfully, we will get the HTTP response status code as 200 OK.

The httpRequest.response object response contains the response data sent from the server. Also, note that we have set the response type as json since we are sending the response in JSON format from our Servlet.

We can also retrieve responses by using:

  • httpRequest.responseText – Returns response in the form of String or text.
  • httpRequest.responseXML – Returns response in the form of XMLDocument.

Finally, It’s time to run the application.

We are using Apache Tomcat to run the application. Following is the page before making the AJAX call to the server.

ajax servlet example

After receiving the response to the browser.

ajax_output2

Conclusion

In this article, we learned how to use the Ajax technique to invoke the backend servlet and retrieve the response from the servlet.