sun.com docs.sun.com My Sun Worldwide Sites

  Previous Contents Next

How the AjaxList Application Works

When the user enters an item in the text field and clicks the Add to List button, the application performs the following tasks:

  1. Generates the Client Event: A client event is generated, thereby calling a JavaScript function that creates the URL to the servlet. This URL contains:

    • The URL pattern that references the servlet, as defined in the web.xml file

    • A request parameter set to the value the user entered.

    • A request parameter set to the command, add, indicating that the servlet must add the value to the list.

  2. Creates and Configures the XMLHttpRequest Object: The JavaScript function mentioned in the previous step calls another function that creates and configures the XMLHttpRequest object.

  3. Sends an Ajax Request: The XMLHttpRequest object sends a POST HTTP request to the servlet, using the URL created in step 1.

  4. Processes the Ajax Request: The doPost method of ListServlet handles the POST HTTP request by creating a List object in the user's HTTP session and adding the item the user entered to the list.

  5. Returns the Response to the Client: The doPost method creates and sends the response, which includes the updated list, back to the client.

  6. Updates the HTML DOM: When the response is successfully returned, the XMLHttpRequest object invokes its callback method, which adds the updated list returned in the response to the HTML DOM of the page.

After the list is displayed in the page, the user can click an item in the list to remove it. Doing this will create another XMLHttpRequest object, which will post another POST HTTP request, this time passing the index of the item to be deleted and the command "remove" as the request parameters.

The doPost method of ListServlet handles the POST HTTP request by getting the index of the item the user selected in the list, removing the item from the list, and sending the updated list in the response.

The remaining sections describe how to perform the following tasks to create the list application. Again, this section is meant to show you how Ajax works so that you can understand the more advanced techniques for instrumenting Ajax behavior in your applications.

  • Generating the Client Event

  • Creating and Configuring the XMLHttpRequest object

  • Sending an Ajax Request

  • Processing the Ajax Request

  • Returning the Response to the Client

  • Updating the HTML DOM

Generating the Client Event

When you click the Add to List button, an onclick JavaScript event is generated. This event causes the submitData function to be called, as shown in the following markup from index.jsp:

<div id="listForm" class="listContainer">
  <form name="autofillform" onSubmit="submitData(); return false;">
    <input id="entryField" type="text" size="20" value="Enter New Value">
    <input type="button" onclick="submitData(); return false;" value="Add to List">
  </form>
  <div id="list" class="listDiv"></div>
</div>

Notice in the markup for the page that there are two div tags, one inside the other. A JavaScript technology function looks for a tag in a page by using the unique IDs of div tags. The outer div tag wraps the form component, which includes the field in which you enter an item, the button to add the item to the list, and the inner div tag. The inner div tag identifies the component that displays the list on the page.

When the user clicks the button, the submitData method is invoked. The submitData function performs these tasks:

  1. Gets the value the user entered into the entryField text field.

  2. Creates a URL composed of: the URL pattern for the servlet, the command request parameter set to add, and the entryField parameter set to the value the user entered in the entryField text field.

  3. Calls the initRequest function with the URL it created in the previous step.

Here is the submitData function from index.jsp:

function submitData() {
    entryField = document.getElementById("entryField");
    var url = "list?command=add&entryField=" + entryField.value;
    initRequest(url);
}

The next section describes how the initRequest function creates and configures the XMLHttpRequest object.

Creating and Configuring the XMLHttpRequest Object

The initRequest function creates an XMLHttpRequest object and uses it to send an Ajax request to the server using the URL that the submitData function passes to the initRequest function.

The following code from index.jsp shows the initRequest function:

<script type="text/javascript">
var isIE;
var list;
var entryField;

function initRequest(url) {
    var list = document.getElementById("list");
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = processRequest;
    req.open("POST", url, true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(null); 

    function processRequest () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                list.innerHTML = req.responseText;
            }
        }
    }
}
</script>

As shown in the preceding code, the initRequest function creates an appropriate XMLHttpRequest object based on the brand of browser client in which the code is running. The function then calls open on the XMLHttpRequest object. The open function takes three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously.

If an interaction is set as asynchronous (true), you must specify a callback function. To specify the callback function, you set the XMLHttpRequest object's onreadystatechange property to the name of a callback function. In this case, the callback function is processRequest. Updating the HTML DOM describes how the callback function works when the server returns the response. The next section explains how the XMLHttpRequest object sends an Ajax request to the server.

Sending an Ajax Request

The initRequest function sends the Ajax request by calling the XMLHttpRequest object's send method with the URL of the location to send the request. In the case of an HTTP GET, the URL argument can be null or you can leave it blank. In the case of the list example, the XMLHttpRequest object is doing a POST because it is sending data that will affect the server-side application state. So the XMLHttpRequest object sends the request to the URL that the submitData function passed to initRequest.

To perform an HTTP POST, you need to set a Content-Type header on the XMLHttpRequest object by using the following statement:

req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

After you've set the request header, you send the request:

req.send(url);

Processing the Ajax Request

Recall that the web.xml file maps ListServlet to the URL pattern, /list:

<servlet-mapping>
    <servlet-name>ListServlet</servlet-name>
    <url-pattern>/list</url-pattern>
</servlet-mapping>

Therefore, when the initRequest function posts a request to the URL list?command=add?entryField=entryField.value, ListServlet processes the request.

The doPost method from ListServlet does the following to process a request to add an item to the list:

  1. Gets the current list from the session.

  2. Gets the value of the command request parameter.

  3. Checks if the list is null and sets a new list into session if there isn't one already.

  4. Tests if the value of the command parameter is set to add.

  5. If the value of the command parameter is add, doPost gets the value of the entryField parameter, which is what the user entered into the text field, and adds the value to the list.

  6. Saves the updated list into session.

Here is the code for the doPost method of ListServlet:

public void doPost(HttpServletRequest request,HttpServletResponse response)
        throws IOException, ServletException {

    HttpSession session = request.getSession();
    list = (java.util.ArrayList)session.getAttribute("list");
    String command = request.getParameter("command");

    if (list == null) {
        list = new java.util.ArrayList();
        session.setAttribute("list", list);
    }

    if ("add".equals(command)) {
        String item = request.getParameter("entryField");
        list.add(item);
    }
    ...
    session.setAttribute("list", list);
}

The next section details how doPost sends the updated list back to the client.

Previous Contents Next
Company Info Contact Terms of Use Privacy Copyright 1994-2007 Sun Microsystems, Inc.