J2EE and AJAX: AJAX with Servlets - AJAX and Servlets in the Real World
(Page 4 of 4 )
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 the picture when the user id is filled and the user moves to the next field. This module contain three major components:
- ValidateAvail.js – JavaScript file containing all the client-sideAJAXfunctions
- Register.html – The registration page
- CheckAvail.java – Servlet that does the server-side processing
So here is the code.
First let's have a look at the ValidateAvail.js. The first thing to do is set up the XMLHttpRequest. It's being handled 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 is 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 pagen"+ 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 let's 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”> </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 the parameter and then checks whether the user id already exists in the database or not, using the business layer class. If it does not exist, then the XML output 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 servlets is just one of the many options available to a JEE developer. In the future I would be discussing other options, including Struts and JSF. Till then…
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |