This Tech Tip reprinted with permission by

AJAX stands for Asynchronous JavaScript and XML. In essence, AJAX is an efficient way for a web application to handle user interactions with a web page -- a way that reduces the need to do a page refresh or full page reload for every user interaction. This enables rich behavior (similar to that of a desktop application or plugin-based web application) using a browser. AJAX interactions are handled asynchronously in the background. As this happens, a user can continue working with the page. AJAX Interactions are initiated by the JavaScript in the web page. When the AJAX interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. AJAX interactions can be used to do things such as validate form entries (while the user is entering them) using server-side logic, retrieve detailed data from the server, dynamically update data on a page, and submit partial forms from the page.

What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers. You might consider using a JavaScript library that abstracts the browser differences and in some cases support older browsers using alternative interaction techniques. For more details, see the AJAX FAQ for the Java Developer

So Where Does Java Technology Fit In?

Java technology and AJAX work well together. Java technology provides the server-side processing for AJAX interactions. It can provide this through servlets, JavaServer Pages (JSP) technology, JavaServer Faces (JSF) technology, and web services. The programming model for handling AJAX requests uses the same APIs that you would use for conventional web applications. JSF technology can be used to create reusable components that generate the client-side JavaScript and corresponding server-side AJAX processing code. Let's look at an example that uses AJAX and servlets.

Autocomplete Example

Imagine a web page in which a user can search for information about an employee. The page includes a field where the user can enter the name of the employee. In this example the entry field has an autocomplete feature. In other words, the user can type in part of the employee name, and the web application attempts to complete the name by listing all employees whose first or last name begins with the characters entered. The autocomplete feature saves the user from having to remember the complete name of the employee or from looking for the name on another page.


Implementing autocomplete in a search field is something that can be performed using AJAX. To do it, you need to provide code on the client and on the server.

On the Client

First, the user specifies the URL of a page that is loaded by the browser. For this example let's assume the page is an HTML page that is generated by a JSF component, servlet, or JSP page. The page contains a form text field that has an attribute onkeyup with the name of a JavaScript function doCompletion(). This function is called each time a key is pressed in the form text field.

    <input type="text"

Let's assume that a user types in an "M" character in the form text field. In response, the doCompletion() function is called which, in turn, initializes an XMLHttpRequest object:

   function initRequest() {
       if (window.XMLHttpRequest) {
           return new XMLHttpRequest();
       else if (window.ActiveXObject) {
           isIE = true;
           return new ActiveXObject("Microsoft.XMLHTTP");

   function doCompletion() {
       if (completeField.value == "") {
       else {
           var url = "autocomplete?action=complete&id=" 
           var req = initRequest();
           req.onreadystatechange = function() {
               if (req.readyState == 4) {
                   if (req.status == 200) {
                   else if (req.status == 204){
 "GET", url, true);

The XMLHttpRequest object is not currently part of standard JavaScript (efforts are underway to standardize it), but is a de facto standard and is the heart of AJAX. This object is responsible for interacting over HTTP with a server-side component (in this case, a servlet).

Three parameters are specified when you create an XMLHttpRequest object: a URL, the HTTP method (GET or POST), and whether or not the interaction is asynchronous. In the XMLHttpRequest example, the parameters are:

  • The URL autocomplete, and the text from the complete-field (an M character):
               var url = "autocomplete?action=complete&id=" 
  • GET, signifying the HTTP interactions uses the GET method, and true, signifying that the interaction is asynchronous:
     "GET", url, true);

A callback function needs to be set when you use asynchronous calls. This callback function is called asynchronously at specific points during HTTP interaction when the readyState property on the XMLHttpRequest changes. In the example the callback function is processRequest(). It's set as the XMLHttpRequest.onreadystatechange property to a function. Notice the call to the parseMessages function when the readState is "4". The XMLHttpRequest.readyState of "4" signifies the successful completion of the HTTP interaction.

The HTTP interaction begins when XMLHttpRequest.send() is called. If the interaction is asynchronous, the browser continues to process events in the page.

On the Server

The XMLHttpRequest makes an HTTP GET request to the URL autocomplete, which is mapped to a servlet called AutoComplete. The doGet() method of the AutoComplete servlet is called. Here is what the doGet() method looks like:

   public void doGet(HttpServletRequest request, 
           HttpServletResponse response
        throws IOException, ServletException 
       String targetId = request.getParameter("id");
       if (targetId != nulltargetId = targetId.trim().toLowerCase();
       Iterator it = employees.keySet().iterator();
       while (it.hasNext()) {
           EmployeeBean e = (EmployeeBean)employees.get(
           if ((targetId != null&&
              (e.getFirstName().toLowerCase ().startsWith(targetId||
              && !targetId.equals("")) {
              sb.append("<id>" + e.getId() "</id>")
              sb.append("<firstName>" + e.getFirstName() 
              sb.append("<lastName>" + e.getLastName() 
              namesAdded = true
       if (namesAdded) { 
                   sb.toString() "</employees>")

As you can see in this servlet, there is nothing really new you need to learn to write server-side code for AJAX processing. The response content type needs to be set to text/xml for cases where you want to exchange XML documents. With AJAX, you can also exchange plain text or even snippets of JavaScript which may be evaluated or executed by the callback function on the client. Note too that some browsers might cache the results, and so it might be necessary to set the Cache-Control HTTP header to no-cache. In this example, the servlet generates an XML document that contains all employees with a first or last name beginning with the character M. Here is an example of an XML document that is returned to the XMLHttpRequest object that made the call:


Returning to the Client

When the XMLHttpRequest object that made the initial call receives the response, it calls the parseMessages() function (see the initialization of the XMLHttpRequest earlier in this example for more details). Here is what the parseMessages() function looks like:

   function parseMessages(responseXML) {
           var employees = responseXML.getElementsByTagName(
       if (employees.childNodes.length > 0) {
       else {
       for (loop = 0; loop < employees.childNodes.length; loop++) {
           var employee = employees.childNodes[loop];
           var firstName = employee.getElementsByTagName(
           var lastName = employee.getElementsByTagName(
           var employeeId = employee.getElementsByTagName(

The parseMessages() function receives as a parameter an object representation of the XML document returned by the AutoComplete servlet. The function programmatically traverses the XML document, and then uses the results to update the contents of the HTML page. This is done by injecting into a

element whose id is "menu-popup" the HTML source for the names in the XML document:

   <div style="position: absolute; 
      top:170px;left:140px" id="menu-popup">
As the user enters more characters, the list shortens. The user can then click on one of the names.

Hopefully by now you realize that AJAX is simply exchanging information over HTTP in the background of a page, and updating that page dynamically based on the results. For more information about AJAX and Java technology, see the technical article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition. Also see the AJAX BluePrints page, and the AJAX FAQ for the Java Developer in Greg Murray's blog.

Running the Sample Code

A sample package accompanies this tip that demonstrates the techniques covered in the tip. You can deploy the sample package on any web container that supports the Servlet 2.4 API (or greater). To install and run the sample:

  1. If you haven't already done so, download GlassFish from the GlassFish Project page. GlassFish supports Servlet 2.5 and the JSP Standard Tag Library (JSTL) "out of the box". If you are using a J2EE 1.4 or Servlet 2.4 container you might need to include the JSTL JAR files in the web/WEB-INF/lib directory.
  2. Set the following environment variables:
    • GLASSFISH_HOME. This should point to where you installed GlassFish (for example C:\Sun\AppServer)
    • ANT_HOME. This should point to where ant is installed. Ant is included in the GlassFish bundle that you downloaded. (In Windows, it's in the lib\ant subdirectory.)
    • JAVA_HOME. This should point to the location of JDK 5.0 on your system.

    Also, add the ant location to your PATH environment variable.

  3. Download the sample file and extract its contents. You should now see the newly extracted directory as <install_dir>\ajax-autocomplete. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be at C:\ajax-autocomplete.
  4. Go to the ajax-autocomplete directory and copy the to a file.
  5. Open the file and set the servlet.jar property to a JAR file that contains the Servlet 2.4 (or greater) API. In the case of GlassFish, the JAR file is <gf_install_dir>/glassfish/lib/javaee.jar, where <gf_install_dir> is where you installed GlassFish. Set the javaee.autodeploy directory to the directory where the web container will auto-deploy the application. On GlassFish this directory is <gf_install_dir>/glassfish/domains/domain1/autodeploy.
  6. Start GlassFish by entering the following command:
          <GF_install_dir>\bin\asadmin start-domain domain1

    where <GFinstall_dir> is the directory where you installed Glassfish.

  7. Use the Ant tool to build and deploy the application. GlassFish has a copy of Ant in the <gf_install_dir>/glassfish/bin/asant directory. You can also download Ant from the Apache Ant Project page.

    To build, enter the following command.


    To deploy the application, enter the following command:

                ant deploy
  8. Open your browser to the following URL: http://localhost:8080/ajax-autocomplete/.

    If you are using NetBeans 4.1 or greater, the sample is included and runnable from the tool by selecting Help -> BluePrints Solutions Catalog. From there select the AJAX -> Autocomplete example and you are done. You can run the example from within NetBeans and modify it if you choose.

    When you run the example it will look as follows:

  9. {mosimage}

    Click on a name in the list to display information about the employee.


    About the Author

    Greg Murray is the servlet specification lead. Greg is a former member of the Java BluePrints team, and was responsible for the web tier recommendations. He is leading the AJAX effort at Sun with the help of the BluePrints team. Greg has experience with internationalization, web services, J2SE standalone clients, and AJAX-based web clients.

    Copyright (c) 2004-2005 Sun Microsystems, Inc.
    All Rights Reserved.