Ajax: Building a dynamic Java application (figure)

Source: Internet
Author: User
Tags add object http post http request implement versions window java web
Ajax| Program | dynamic
In WEB application development, page overload cycling is one of the biggest barriers to use, for Java? It's also a daunting challenge for developers. In this series, author Philip McCarthy describes a pioneering way to create a dynamic application experience.
Ajax (asynchronous JavaScript and XML) is a programming technique that allows you to combine Java technology, XML, and JavaScript into Java-based WEB applications to break the paradigm of page overloading.
  
Ajax (that is, asynchronous JavaScript and XML) is a Web application development tool that uses client script to exchange data with a Web server. Therefore, you can dynamically update Web pages without having to use a full page refresh that interrupts interaction. With Ajax, you can create richer, more dynamic WEB application user interfaces, with immediacy and availability even closer to native desktop applications.
  
Ajax is not a technology, but more like a pattern--a way to identify and describe useful design techniques. Ajax is novel, because many developers are just beginning to know about it, but all the components that implement AJAX applications have been around for several years. It is now being valued because of the great dynamic Web UI that emerged from Ajax Technologies in 2004 and 2005, most notably Google's GMail and Maps apps, and Flickr, the photo-sharing site. These user interfaces are groundbreaking enough, some developers call it "Web 2.0," so the interest in Ajax applications is soaring.
  
In this series, I will provide all the tools you need to develop your application using Ajax. In the first article, I'll explain the concepts behind Ajax and demonstrate the basic steps of creating an Ajax interface for java-based WEB applications. I'll use code samples to demonstrate server-side Java code and client JavaScript that make Ajax applications so dynamic. Finally, I'll point out some of the drawbacks of the AJAX approach, as well as some of the broader usability and accessibility issues that should be considered when creating AJAX applications.
  
   a better shopping cart
  
You can use Ajax to enhance traditional Web applications, simplifying interactions by eliminating page loading. To illustrate this, I take a simple shopping cart example, which is dynamically updated when I add an item to it. If the technology is integrated into an online store, users can continuously browse and add items to the cart without having to wait for full page updates after each click. Although some of the code in this article is specific to the shopping cart example, the techniques demonstrated can be applied to any AJAX application. Listing 1 shows the HTML code used in the shopping cart example, which is used throughout the article.
  
Listing 1. A piece about the shopping cart sample
  
<!--Table of products from store ' s 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 >add to Cart</button>
</td>
</tr>
...
  
<!--representation of shopping cart, updated asynchronously-->
<ul id= "Cart-contents" >
  
<!--List-items'll be added this 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 Roundtrip process
  
The Ajax interaction begins with a JavaScript object called XMLHttpRequest. As the name suggests, it allows client script to execute HTTP requests and parse XML server responses. The first step in the Ajax roundtrip process is to create an instance of XMLHttpRequest. Sets the HTTP method (get or POST) that the request uses on the XMLHttpRequest object and the destination URL.
  
Now, do you remember that Ajax's first A is for asynchronous (asynchronous)? When sending an HTTP request, you do not want the browser to hang waiting for the server to respond. Instead, you want the browser to continue to respond to the user's interaction with the page and then process the server response when it arrives. To implement this requirement, you can register a callback function on the XMLHttpRequest and assign XMLHttpRequest asynchronously. The control then returns to the browser, and the callback function is invoked when the server response arrives.
  
On a Java Web server, the request arrives like any other httpservletrequest. After parsing the request parameters, the servlet invokes the necessary application logic, serializes the response into XML, and writes the XML to the HttpServletResponse.
  
When you return to the client, the callback function registered on the XMLHttpRequest is now invoked to handle the XML document returned by the server. Finally, the user interface is updated by using JavaScript to manipulate the HTML DOM of the page based on the data returned by the server. Figure 1 is a sequential diagram of the Ajax round-trip process.
  
   Figure 1. Ajax Roundtrip process
  
Now you have a high level of understanding of the Ajax round-trip process. I'll zoom in on each of these steps for a more detailed look. If you get lost in the process, look back at the figure 1--because of the asynchronous nature of the Ajax approach, the order is not very simple.
  
   Assign XMLHttpRequest
  
I'll start with the starting point of the Ajax sequence: creating and assigning XMLHttpRequest from the browser. Unfortunately, different browsers create XMLHttpRequest in a variety of ways. The JavaScript function in Listing 2 eliminates these browser-dependent techniques that detect the correct way to use the current browser and return a xmlhttprequest that can be used. It's best to treat it as a secondary code: just copy it to the JavaScript library and use it when you need to xmlhttprequest it.
  
Listing 2. Create a XMLHttpRequest across browsers
  
/*
* Returns A new XMLHttpRequest object, or False if this browser
* doesn ' t 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 a xmlhttprequest with ActiveX
}
}
}
  
return xmlreq;
}
  
Later I will discuss techniques for dealing with browsers that do not support XMLHttpRequest. Currently, the example assumes that the Newxmlhttprequest function in Listing 2 always returns the XMLHttpRequest instance.
  
Returning to the example shopping cart scene, I want to start Ajax interaction when the user clicks Add to Cart on the directory item. The onclick processing function named AddToCart () is responsible for updating the status of the shopping cart through Ajax calls (see Listing 1). As shown in Listing 3, the first thing AddToCart () needs to do is to get the XMLHttpRequest object by invoking the Newxmlhttprequest () function of Listing 2. Next, it registers a callback function to receive the server response (I will explain this step in detail later; see listing 6).
  
Because the request modifies the state on the server, I will do the work with an HTTP POST. Sending data over a POST requires three steps. First, you need to open a POST connection to the server resource that you want to communicate--in this case, the server resource is a servlet that maps to the URL cart.do. I then set a header on the XMLHttpRequest to indicate that the content of the request is the form-encoded data. Finally, I send the request with the form-encoded data as the requesting body.
  
Listing 3 puts these steps together.
  
Listing 3. Assign 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 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 an Ajax roundtrip process that creates and assigns HTTP requests from clients. Next is the Java servlet code that is used to process the request.
  
   servlet Request Processing
  
Processing XMLHttpRequest with a servlet is the same as processing a normal browser HTTP request. can be obtained with Httpservletrequest.getparameter () on POST request

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.