Ajax for Java programmers: Build Dynamic Java programs

Source: Internet
Author: User

Ajax (Asynchronous JavaScript and XML) is a means of Web application development. It uses client scripts to exchange data with the Web server. Therefore, you can dynamically update Web pages without refreshing the complete page that interrupts interaction. With Ajax, you can create a richer and more dynamic Web application user interface, and its real-time and availability can even be close to the local desktop application.

Ajax is not a technology, but more like a pattern-a way to identify and describe useful design technologies. Ajax is novel because many developers have just begun to understand it, but all the components that implement Ajax applications have existed for several years. It is currently valued because some Ajax-based Dynamic Web UIS appeared in 2004 and 2005. The most famous is Google's GMail and Maps applications, as well as the photo sharing site Flickr. These user interfaces are ground-breaking. Some developers call them "Web 2.0", so their interest in Ajax applications is increasing rapidly.

In this series, I will provide all the tools required to develop applications using Ajax. In the first article, I will explain the concepts behind Ajax and demonstrate the basic steps for creating an Ajax interface for Java-based Web applications. I will use the sample code to demonstrate the dynamic server-side Java code and client JavaScript For Ajax applications. Finally, I will point out some shortcomings in the Ajax method, as well as some broader availability and access issues that should be considered when creating Ajax applications.

  Better shopping cart

You can use Ajax to enhance traditional Web applications and simplify interaction by eliminating page loading. To demonstrate this, I use a simple shopping cart example, which will be dynamically updated when a project is added to it. If this technology is integrated into online stores, users can continuously browse and add projects to the cart without waiting for complete page updates after each click. Although some code in this article is specific to the shopping cart example, the demonstrated technology can be applied to any Ajax application. Listing 1 shows the HTML code used in the shopping cart example. This HTML is used throughout the article.

Listing 1. related parts of the shopping cart example

<!-- Table of products from stores catalog, one row per item -->
<th>Name</th> <th>Description</th> <th>Price</th> <th></th>
...
<tr>
<!-- Item details -->
<td>Hat</td> <td>Stylish bowler hat</td> <td>$19.99</td>
<td>
<!-- Click button to add item to cart via Ajax request -->
<button onclick="addToCart(hat001)">Add to Cart</button>
</td>
</tr>
...

<!-- Representation of shopping cart, updated asynchronously -->
<ul id="cart-contents">

<!-- List-items will be added here for each item in the cart -->

</ul>

<!-- Total cost of items in cart displayed inside span element -->
Total cost: <span id="total">$0.00</span>

  Ajax round-trip Process

Ajax interaction begins with a JavaScript Object called XMLHttpRequest. As the name suggests, it allows client scripts to execute HTTP requests and parse XML server responses. The first step in the Ajax round-trip process is to create an XMLHttpRequest instance. Set the HTTP method (GET or POST) and target URL used by the request on the XMLHttpRequest object.

Now, do you still remember that the first Ajax a represents asynchronous? When sending an HTTP request, you do not want the browser to wait for the server to respond. On the contrary, you want the browser to continue responding to the interaction between the user and the page, and then process it when the server responds. To achieve this, you can register a callback function on XMLHttpRequest and asynchronously assign XMLHttpRequest. Then the control will return to the browser. When the server responds, the callback function will be called.

On the Java Web server, requests arrive at the same time as other HttpServletRequest requests. After parsing the request parameters, the servlet calls the necessary application logic, serializes the response to XML, and writes the XML to HttpServletResponse.

When I return to the client, I now call the callback function registered on XMLHttpRequest to process the XML document returned by the server. Finally, use JavaScript to manipulate the html dom of the page based on the data returned by the server to update the user interface. Figure 1 shows the order of the Ajax round-trip process.


Figure 1. Ajax round-trip Process
Now you have a high-level understanding of the Ajax round-trip process. Next, I will zoom in on each step for more detailed observation. If you are confused during the process, please look back at Figure 1-the order is not very simple because of the asynchronous nature of the Ajax method.

Dispatch XMLHttpRequest

I will start with the Ajax sequence: Create and dispatch XMLHttpRequest from the browser. Unfortunately, different browsers use different methods to create XMLHttpRequest. The JavaScript Functions in Listing 2 eliminate these browser-dependent skills, which can detect the correct method to be used by the current browser and return a usable XMLHttpRequest. It is better to use it as a helper code: Just copy it to the JavaScript library and use it when XMLHttpRequest is required.

Listing 2. Creating cross-browser XMLHttpRequest

/*
* Returns a new XMLHttpRequest object, or false if this browser
* doesnt support it
*/
function newXMLHttpRequest() {

 var xmlreq = false;

 if (window.XMLHttpRequest) {

  // Create XMLHttpRequest object in non-Microsoft browsers
  xmlreq = new XMLHttpRequest();

 } else if (window.ActiveXObject) {

  // Create XMLHttpRequest via MS ActiveX
  try {
   // Try to create XMLHttpRequest in later versions
   // of Internet Explorer

   xmlreq = new ActiveXObject("Msxml2.XMLHTTP");

  } catch (e1) {

   // Failed to create required ActiveXObject

   try {
    // Try version supported by older versions
    // of Internet Explorer
    xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e2) {
    // Unable to create an XMLHttpRequest with ActiveX
   }
  }
 }
 return xmlreq;
}

Later I will discuss the technology to deal with browsers that do not support XMLHttpRequest. Currently, the example assumes that the newXMLHttpRequest function in Listing 2 always returns the XMLHttpRequest instance.

Return to the example shopping Cart scenario. I want to enable Ajax interaction when you click Add to Cart in the Directory Project. The onclick handler named addToCart () is used to update the shopping cart status by calling Ajax (see Listing 1 ). As shown in listing 3, the first thing addToCart () needs to do is to call the newXMLHttpRequest () function in Listing 2 to get the XMLHttpRequest object. Next, it registers a callback function to receive server responses (I will explain this step in detail later; see Listing 6 ). Because the request will modify the status on the server, I will use HTTP POST to do this. Three steps are required to send data through POST. First, you need to open the POST connection to the server resource to be communicated-in this example, the server resource is a servlet mapped to the URL cart. do. Then, I set a header on XMLHttpRequest to indicate that the request content is form-encoded data. Finally, I use form-encoded data as the request body to send a request.

Listing 3 puts these steps together.

Listing 3. Assigning Add to Cart XMLHttpRequest

/*
* Adds an item, identified by its product code, to the shopping cart
* itemCode - product code of the item to add.
*/
function addToCart(itemCode) {

 // Obtain an XMLHttpRequest instance
 var req = newXMLHttpRequest();

 // Set the handler function to receive callback notifications
 // from the request object
 var handlerFunction = getReadyStateHandler(req, updateCart);
 req.onreadystatechange = handlerFunction;

 // Open an HTTP POST connection to the shopping cart servlet.
 // Third parameter specifies request is asynchronous.
 req.open("POST", "cart.do", true);

 // Specify that the body of the request contains form data
 req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 // Send form encoded data stating that I want to add the
 // specified item to the cart.
 req.send("action=add&item="+itemCode);
}

This is the first part of the Ajax round-trip process, that is, creating and dispatching HTTP requests from the client. The following is the Java servlet code used to process the request.
Servlet Request Processing

Using servlet to process XMLHttpRequest is the same as processing HTTP requests in normal browsers. You can use HttpServletRequest. getParameter () to obtain the form encoding data sent in the POST Request body. Ajax requests are put in the same HttpSession as regular Web requests from applications. This is useful for the example shopping cart scenario, because it allows me to encapsulate the shopping cart status in JavaBean and maintain this status between requests in sessions.

Listing 4 is part of a simple servlet that processes Ajax requests and updates the shopping cart. The Cart bean is obtained from the user session and its status is updated according to the request parameters. Then the Cart is serialized into XML, and the XML is written into ServletResponse. It is important to set the response content type to application/xml. Otherwise, XMLHttpRequest will not parse the response content into xml dom.

Listing 4. servlet code for processing Ajax requests

public void doPost(HttpServl

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.