Non-obtrusiveness, responsiveness and high interactivity are the areas where desktop applications still have an edge over the web-applications. The intelligent use of JavaScript can create highly interactive web-sites. However, responsiveness and non-obtrusiveness would still be a distant dream. The responsiveness can be achieved by careful implementation at server-side by using technology such as J2EE that uses threading mechanism to service requests. But, to achieve non-obtrusiveness, a component is required that can provide asynchronous means of communication so that complete re-rendering of a page during the response phase can be bypassed. That is where AJAX comes into picture. AJAX provides asynchronous communication service through JavaScript and XML. Thus a good combination can be formed by using AJAX at client-side and Servlet at server-side providing non-obtrusive, responsive and highly interactive web experience. In this discussion, I would be focusing on utilizing such a winning combination. The first section would be detailing the steps required for setting up of application for utilizing AJAX along with servlet. In second and the last section I would be developing a registration module that would use AJAX to check the availability of the username. That’s what’s in store for this discussion.

AJAX and Servelets- The Steps for Implementation:

AJAX or Ajax is really not a technology in itself but it is a combination of existing technologies. These form the basis of the asynchronous communication, XML and HTML manipulation. So lets have look at these components:

1. XML

2. XMLHttpRequest (JavaScript)

3. HTML/XHTML with CSS

4. Server-side component.

The steps to implement AJAX cover these entire components. The JavaScript communicates with the server using XMLHttpRequest, receives response in the form of XML from the server side component which is used by the JavaScript to manipulate the HTML to present data to the user. That is the complete cycle of AJAX request-response cycle in nut-shell. The implementation that gives raise to the aforementioned cycle constitutes the following steps:

1. Setting up the XMLHttpRequest

2. Calling the server-side component

3. Registering and implementing call-back handler and at the server side

4. Generate the XML response.

How the four components fits with the implementation steps is detailed below.

1. Setting up the XMLHttpRequest:

The very first step of AJAX setup comes in the form of instantiating XMLHttpRequest. It exists in two varieties- first as an ActiveX control and second as a JavaScript object. The Internet Explorer considers it as an ActiveX while Mozilla, Firefox and Opera consider it as a JavaScript. So to set up XMLHttpRequest the browser type has to be checked. The best way to check the type is to determine whether the client browser supports ActiveX or not. If ActiveX is supported then instantiate using CreateObject() method otherwise use XMLHttpRequest’s constructor to do the same. In code, it would be:

var xmlHttp;

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

else if(window.XMLHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

Instead of directly using else part, the check can be done on the browser supporting XMLHttpRequest as an object or not. To instantiate the XMLHttpRequest object as an ActiveX, then the object name which in this case is Microsoft.XMLHTTP, has to be passed to the CreateObject method. To instantiate it using the constructor, new XMLHttpRequest() has to be used. That completes the setting up step.

2. Calling Server-Side Component:

To make a call to the server-side component (in this case servlets) the methods of XMLHttpRequest instance have to be used. Which method to be used depends on the type of method to be used. following are the methods:

i. setRequestHeader

ii. open

iii.send

The first method comes into picture when the method of HTTP request has to be POST. The parameters taken by the second and third methods change according to the method used.

i. setRequestHeader:

It sets the value of the header given as parameter. This method takes two parameters-the name of the request header, the value of the header. This method comes into picture when POST method is used. For example, if POST has to be used, the statement would be:

xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-

urlencoded; charset=UTF-8″);

The first parameter sets the name of the header as Content-Type and its value as application/x-www-form-urlencoded. Also its sets the character set of the content as UTF-8. But it is important to call open before setting the header.

ii. open:

This is the method that actually sets up the communication with the server. The URL corresponding to the servlet is given as the second of the parameters. The first parameter is the type of the method to communicate with the server. It can be either GET or POST or PUT. If GET is used, the data sent as query string by appending it to the URL i.e. the first parameter. The third parameter, which takes a Boolean value decides whether the communication would be synchronous or asynchronous. A true value makes the communication asynchronous whereas a false value makes the communication synchronous. The last two optional parameters are required only when the server requires authentication. For example, to call a servlet having a URL http://localhost:81/SCM/register having asynchronous communication, the statement would be:

xmlHttp.open(“GET”,”http://localhost:81/SCM/register?user=”+user, true);

Here the value to be sent to the server is passed as a query string appended to the URL.

iii. send:

This sends the data to the server when the method is POST. If it is GET, then

null is send to the server. In case of POST, a string of name-value pair is set as its parameter. For example, to send user name and password to the server and the method is POST, the statements would be:

var params=”user=”+user+”&pass=”+pass;

xmlHttp.send(params)

That completes setting up the XMLHttpRequest.

3. Registering and implementing call-back handler:

There needs to be a handler that can be invoked when the response arrives. It is the callback handler. A callback handler is simply a function that is registered with the system and that is invoked by the system when the event for which it is registered. So in this case the event is arrival of data along with the response. To handle this event, a function has to be registered with the XMLHttpRequest which is done by the onreadystatechange property of XMLHttpRequest. So to register a function named handleStateChange(), the statement would be:

xmlHttp.onreadystatechange=handleStateChange;

The next step is to implement the handler. The basic functionalities that a handler should implement are retrieving data from XML response sent from the servlet and manipulating the current page on the browser according to the data received from the server. For example, to display the result coming from the server on the page, the code would be:

function handleStateChange()

{

if(xmlHttp.readyState==4)

{

if(xmlHttp.status==200)

{

document.getElementById(“results”).innerHTML=xmlHttp.responseText;

}

else

{

alert(“Error loading page\n”+ xmlHttp.status +”:”+ xmlHttp.statusText);

}

}

}

Here the element having the id results is a <div> tag. So whatever be the data coming from the server is displayed as child nodes of the results. The three properties that are being used here are-readyState, status and responseText. The readyState specifies whether data load operation is successful or not. Any value except 4 indicates that data is not yet available. Even then if the data contains a ‘file not found message’, then also the next part wouldn’t work as required. Hence, it is always better to check the status. The data is usable only if the status is 200. The next part is to extract the data and use it. The XMLHttpRequest instance has two properties-responseText and responseXML to extract data from the response. If data is in the form of text then responseTest can be used otherwise responseXML can be used.

The only piece of the puzzle is the server-side part. That’s what coming up.

4. Generate the XML response:

Whatever be the server-side technology, the implementation has to generate XML. In this case the technology is servlet. To generate the response the three things have to be done- first set the content type to text/xml, secondly get a writer object and then set the XML into the response using the writer object. The code would be something like:

response.setContentType(“text/xml”);

response.getWriter().write(“<valid>true</valid>”);

where response is an object of HttpServletResponse. That’s it. In the next section I would be putting it all together to develop a registration module that would check the availability of the user id.

AJAX and Servlets- In the Real World:

The module to be developed has to check the availability of a user id. Why use AJAX here? The answer is that if the user id is already taken, then it is always better to tell the user as soon as possible. By using AJAX this can be done once the user id has been entered. The AJAX would come into picture when the user id is filled and the user moves to next field. This module contain three major components:

1. ValidateAvail.js – JavaScript file containing all the client-side AJAX functions

2. Register.html – The registration page

3. CheckAvail.java – Servlet that does the server-side processing

So here is the code.

First lets have a look at the ValidateAvail.js. The first thing to do is setting up the XMLHttpRequest. Its being done by the following function:

var xmlHttp;// global instance of XMLHttpRequest

function createXmlHttpRequest()

{

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

else if(window.XMLHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

}

Next the function that sets up the communication with the server

function startRequest()

{

createXmlHttpRequest();

var u1=document.f1.user.value;

xmlHttp.open(“GET”,”http://localhost:8080/SCM/checkAvail?user=”+u1

,true)

xmlHttp.onreadystatechange=handleStateChange;

xmlHttp.send(null);

}

This function also registers the callback handler which is handleStateChange. Next is the code for the handler.

function handleStateChange()

{

if(xmlHttp.readyState==4)

{

if(xmlHttp.status==200)

{

var message =

xmlHttp.responseXML

.getElementsByTagName(“valid”)[0]

.childNodes[0].nodeValue;

document.getElementById(“results”).innerHTML=message;

}

else

{

alert(“Error loading page\n”+ xmlHttp.status +”:”+

xmlHttp.statusText);

}

}

}

After checking the readyState and the status, the data is extracted from the response using JavaScript XML parsing APIs. The data is then passed on to the HTML page using DOM API. Now lets have a look at the HTML page. Only the relevant portion is being shown.

<tr>

<td width=”36%”>Userid</td>

<td width=”33%”>

<input type=”text” name=”user” onBlur=” startRequest();”/>

</td>

<td width=”31%” id=”results”>&nbsp;</td>

</tr>

The startRequest() function is called on the Blur event. Thus starting the AJAX process.

The next in line is the servlet code. Here it is:

package someorg;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class CheckAvail extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

UserOp userOp=new UserOp();//business layer class.

//implementation not shown for brevity

//get the userId

String targetId = request.getParameter(“user”);

//check the id. If it is not existing already then return true else false

if ((targetId != null) && !userOp.containsKey(targetId.trim())) {

response.setContentType(“text/xml”);

response.setHeader(“Cache-Control”, “no-cache”);

response.getWriter().write(“<valid>true</valid>”);

} else {

response.setContentType(“text/xml”);

response.setHeader(“Cache-Control”, “no-cache”);

response.getWriter().write(“<valid>false</valid>”);

}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

doGet(request, response);

}

}

}

The servlet retrieves the value of parameter and then checks whether the user id is already existing in the database or not using the business layer class. If it does not exists, then the XML out put contains true as the node value of the node <valid> otherwise it would contain the value false. That’s it. This brings us to the end of this discussion. Using AJAX with servlet is just one of the many option available to a JEE developer. In the future I would be discussing other options including Struts and JSF. Till then…