Java
  Home arrow Java arrow Page 4 - J2EE and AJAX: AJAX with Servlets
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

J2EE and AJAX: AJAX with Servlets
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 76
    2006-07-12

    Table of Contents:
  • J2EE and AJAX: AJAX with Servlets
  • AJAX and Servlets: the Steps for Implementation
  • Steps for Implementation continued
  • AJAX and Servlets in the Real World

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    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.

       · HiAjax is one of the hottest tech. in the current market. In this article I have...
       · Hi, Techie AjaxGood to see your simple and yet best explanation method of Ajax new...
       · HiThanks for your comments. Yes you can send HTML as response. However instead of...
       · Appreciate your quick reply,Could you pls, send me a sample code sinppet.Servlet...
       · hello Mr.Rajashekar gaaru,how ru?my name is bharath.Really u did experiments...
       · Hi Mr.Rajashekar,Your code is simply superb and easy to understand.But when i...
       · Thanks,It is very good tutorial which contains all the basic thing.The way you have...
     

    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...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway