Saturday, 16 April 2011

Getting Started with AJAX using Java


AJAX is an acronym for Asynchronous JavaScript And XML. AJAX provides an ability to communicate with the server asynchronously. Here asynchronous is the keyword. To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
This is achieved by AJAX using XMLHttpRequest object. Your browser provides the capability for XMLHttpRequest object. Most modern browsers provides support for XMLHttpRequest. This object helps for http request and process XML response. It is not mandatory that you should use only XML. Simple text can also be used in Ajax but which is uncommon.
Before continuing with the article, I assume that you have basic knowledge about http headers, request response mechanism, different method types and response codes. If you lack knowledge in these areas, it is better to update them before proceeding. If you cant read GET, POST, HTTP status 200 OK and response Content-Type: text/html, xml then you must know these topics before learning AJAX. I am not writing in detail about them here, because each one of them calls for a detailed separate article.
Let me write a HelloWorld ajax web application to demonstrate basics. We shall have a button with name ‘Say Hello!’ On click of that button, without reloading the whole page we will display “Hello World!” by replacing the ‘Say Hello!’ button. Following source code listing contains complete code of sample web application.


index.jsp


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Getting Started with AJAX using JAVA</title>
  <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
  <script type="text/javascript"language="javascript" src="ajax.js"></script>
</head>
<body>
  <div>Getting Started with AJAX using JAVA: Hello World!</div>
  <div id="hello"><button type="button"onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>

index.jsp contains a div ‘hello’. That is the div which XMLHttpRequest object is going to overwrite with response from Servlet. On click of the button we call a java script function makeRequest(). Until now, there is nothing special. Its usual jsp and javascript call. Ajax is not in the picture.

Now go through makeRequest() given below. Inside that we call getXMLHttpRequest() which returns a XMLHttpRequest object. That can be used as a utility method in all your AJAX programs. Thats an attempt to standardization. Different versions of browsers provide different ways of creating XMLHttpRequest. We are covering all possible combinations inside that method.

Once we get XMLHttpRequest object, we need to register a function which will be called on state change. Now its time to explain in detail about XMLHttpRequest object.


XMLHttpRequest properties and events

XMLHttpRequest consists of properties readyState, status, statusText, responseText and responseXML.
  • readyState denotes states as 0 – UNINITIALIZED, 1 – LOADING, 2 – LOADED, 3 – INTERACTIVE, 4 – COMPLETE.
  • status is HTTP status code for the response
  • statusText is HTTP status message for the status code
  • responseText is response text from server
  • responseXML is DOM document object of reponse XML document from server
XMLHttpRequest contains an event ‘onreadystatechange’. It is invoked whenever ‘readyState’ property given above changes.
We need to register a function for the above event ‘onreadystatechange’. In our makeRequest(), after getting xmlHttpRequest object we register getReadyStateHandler(xmlHttpRequest). Therefore whenever there is a state change, this function will be called by the XMLHttpRequest / browser.
After registering the callback funtion we set the request url as the HelloWorld servlet. In web.xml we have done the servlet mapping for that servlet.
In getReadyStateHandler function, if readyState is 4 and http status code is 200 then we set the reponse text from XMLHttpRequest object to the div hello in index.jsp.


ajax.js


/*
 * creates a new XMLHttpRequest object which is the backbone of AJAX,
 * or returns false if the browser doesn't support it
 */
function getXMLHttpRequest() {
  var xmlHttpReq = false;
  // to create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
  else if (window.ActiveXObject) {
    try {
      // to create XMLHttpRequest object in later versions
      // of Internet Explorer
      xmlHttpReq = newActiveXObject("Msxml2.XMLHTTP");
    catch (exp1) {
      try {
        // to create XMLHttpRequest object in older versions
        // of Internet Explorer
        xmlHttpReq = newActiveXObject("Microsoft.XMLHTTP");
      catch (exp2) {
        xmlHttpReq = false;
      }
    }
  }
  return xmlHttpReq;
}
/*
 * AJAX call starts with this function
 */
function makeRequest() {
  var xmlHttpRequest = getXMLHttpRequest();
  xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
  xmlHttpRequest.open("POST","helloWorld.do"true);
  xmlHttpRequest.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
  xmlHttpRequest.send(null);
}
/*
 * Returns a function that waits for the state change in XMLHttpRequest
 */
functiongetReadyStateHandler(xmlHttpRequest) {
  // an anonymous function returned
  // it listens to the XMLHttpRequest instance
  return function() {
    if (xmlHttpRequest.readyState == 4) {
      if (xmlHttpRequest.status == 200) {
        document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
      else {
        alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
      }
    }
  };
}
A simple Hello World servet sending response as Hello World! as text.


HelloWorld.java


package com.vaani.sample.ajax;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
  /**
   * A simple HelloWorld Servlet
   */
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws java.io.IOException {
    res.setContentType("text/html");
    res.getWriter().write("Hello World!");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws java.io.IOException {
    doPost(req, res);
  }
}

See web.xml and response here.

No comments:

Post a Comment