J2EE and AJAX: AJAX with Servlets - Steps for Implementation continued
(Page 3 of 4 )
Registering and implementing the 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 invoked by the system when the event for which it is registered occurs. So in this case the event is the 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 the 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 the 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 pagen"+ xmlHttp.status +":"+ xmlHttp.statusText);
}
}
}
Here the element having the id results is a <div> tag. So whatever may 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 the 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, 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 step 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 left is the server-side part. That’s what is coming up.
Generating the XML response
Whatever may be the server-side technology, the implementation has to generate XML. In this case the technology is servlet. To generate the response, three things must be done: first, set the content type to text/xml; second, get a writer object; and third, set the XML into the response using the writer object. The code will be something like this:
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 will put it all together to develop a registration module that will check the availability of the user id.
Next: AJAX and Servlets in the Real World >>
More Java Articles
More By A.P.Rajshekhar