Home arrow Java arrow Page 4 - J2EE and AJAX: AJAX with Servlets
JAVA

J2EE and AJAX: AJAX with Servlets


Using AJAX with servlets is an excellent option for a J2EE developer. By using AJAX at client-side and a servlet at server-side, you can provide your users with a highly responsive and interactive web experience. This tutorial explains how.

Author Info:
By: A.P.Rajshekhar
Rating: 4 stars4 stars4 stars4 stars4 stars / 139
July 12, 2006
TABLE OF CONTENTS:
  1. · J2EE and AJAX: AJAX with Servlets
  2. · AJAX and Servlets: the Steps for Implementation
  3. · Steps for Implementation continued
  4. · AJAX and Servlets in the Real World

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
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:

  1. ValidateAvail.js – JavaScript file containing all the client-sideAJAXfunctions
  2. Register.html – The registration page
  3. 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”>&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 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.

blog comments powered by Disqus
JAVA ARTICLES

- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...
- Generics and Limitations in Java
- Getting Started with Java Web Development in...

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials