Ajax for Java developers: Build Dynamic Java applications

Source: Internet
Author: User

Ajax paves the way for better Web Applications

 

In web application development, page reload loop is the biggest obstacle to use, and it is also a severe challenge for Java developers. In this series, the author Philip McCarthy introduced a groundbreaking way to create a dynamic application experience. Ajax (Asynchronous JavaScript and XML) is a programming technology that allows Java, XML, and JavaScript to be combined for Java-based web applications to break the page overload paradigm.

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 likeMode-- A method for identifying and describing 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 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 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 startedXMLHttpRequest. 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 createXMLHttpRequest. InXMLHttpRequestSet the HTTP method used by the request on the object (GETOrPOST) And the target URL.

Now, you still remember the first AjaxAYesAsynchronous)? 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 meet this requirement, you canXMLHttpRequestRegister a callback function, and then asynchronously assignXMLHttpRequest. Then the control will return to the browser. When the server responds, the callback function will be called.

On the Java Web server, requests are the same as otherHttpServletRequestSame arrival. After parsing the request parameters, the servlet calls the necessary application logic, serializes the response to XML, and writes the XMLHttpServletResponse.

When you return to the clientXMLHttpRequestTo process the XML file 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 from the starting point of the Ajax sequence: Create and dispatchXMLHttpRequest. Unfortunately, different browsers are createdXMLHttpRequestMethods are different. 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 usableXMLHttpRequest. It is better to use it as a helper code: Just copy it to the Javascript library andXMLHttpRequestYou can use it.

Listing 2. Creating cross-browser XMLHttpRequest

/* * 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 an XMLHttpRequest with ActiveX      }    }  }  return xmlreq;}  

I will discuss how to deal with those unsupported laterXMLHttpRequestBrowser technology. Currently, the example assumes thatnewXMLHttpRequestFunction always returnsXMLHttpRequestInstance.

Return to the example shopping cart scenario. I want to enable Ajax interaction when you click Add to cart in the Directory Project. NameaddToCart()OfonclickThe handler function updates the status of the shopping cart by calling Ajax (see Listing 1 ). As shown in listing 3,addToCart()The first thing to do is to callnewXMLHttpRequest()FunctionXMLHttpRequestObject. 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 serverPOSTDo this. PassPOSTSend data in three steps. First, you need to openPOSTConnection -- in this example, the server resource is mapped to a URLcart.doServlet. ThenXMLHttpRequestSet a header 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

Processing with ServletXMLHttpRequest. AvailableHttpServletRequest.getParameter()Get the form encoding data sent in the POST Request body. Ajax requests are put in the same way as regular Web requests from applicationsHttpSession. 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.CartBean is obtained from user sessions and its status is updated based on request parameters. ThenCartSerialized into XML and written into XMLServletResponse. It is important to set the response content typeapplication/xmlOtherwiseXMLHttpRequestThe response content is not parsed into xml dom.

Listing 4. servlet code for processing Ajax requests

public void doPost(HttpServletRequest req, HttpServletResponse res)                        throws java.io.IOException {  Cart cart = getCartFromSession(req);  String action = req.getParameter("action");  String item = req.getParameter("item");    if ((action != null)&&(item != null)) {    // Add or remove items from the Cart    if ("add".equals(action)) {      cart.addItem(item);    } else if ("remove".equals(action)) {      cart.removeItems(item);    }  }  // Serialize the Cart's state to XML  String cartXml = cart.toXml();  // Write XML to response.  res.setContentType("application/xml");  res.getWriter().write(cartXml);}

Listing 5 showsCart.toXml()Sample XML generated by the method. It is very simple. Note:cartElementgeneratedAttribute, which isSystem.currentTimeMillis()A timestamp generated.

Listing 5. XML serialization example of the cart object

<?xml version="1.0"?><cart generated="1123969988414" total="$171.95">  <item code="hat001">    <name>Hat</name>    <quantity>2</quantity>  </item>  <item code="cha001">    <name>Chair</name>    <quantity>1</quantity>  </item>  <item code="dog001">    <name>Dog</name>    <quantity>1</quantity>  </item></cart>

If you view cart. Java in the application source code (which can be obtained from the download section), you can see that the XML generation method is to add strings together. Although this example is sufficient, it is the worst way to generate xml from Java code. I will introduce some better methods in the next phase of this series.

Now you knowCartServletResponseXMLHttpRequest. The next thing is to return to the client to view how to update the Page Status with XML responses.


Use JavaScript For Response Processing

XMLHttpRequestOfreadyStateAttribute is a value that indicates the status of the request lifecycle. It changes from 0 (indicating "not initialized") to 4 (indicating "completed "). Each timereadyStateWhen changing,readystatechangeThe event is triggeredonreadystatechangeThe event processing function specified by the property is called.

In listing 3, you can see how to callgetReadyStateHandler()Function to create an event handler. Then assign the event handleronreadystatechangeAttribute.getReadyStateHandler()Taking advantage of the fact that a function is a level-1 object in JavaScript. This means that the function can be a parameter of other functions, or you can create and return other functions.getReadyStateHandler()The job is to return a function, checkXMLHttpRequestWhether the process has been completed and the XML response is passed to the event processing function specified by the caller. Listing 6 isgetReadyStateHandler().

Listing 6. getreadystatehandler () function

/* * Returns a function that waits for the specified XMLHttpRequest * to complete, then passes its XML response to the given handler function. * req - The XMLHttpRequest whose state is changing * responseXmlHandler - Function to pass the XML response to */function getReadyStateHandler(req, responseXmlHandler) {  // Return an anonymous function that listens to the   // XMLHttpRequest instance  return function () {    // If the request's status is "complete"    if (req.readyState == 4) {            // Check that a successful server response was received      if (req.status == 200) {        // Pass the XML payload of the response to the         // handler function        responseXmlHandler(req.responseXML);      } else {        // An HTTP problem has occurred        alert("HTTP error: "+req.status);      }    }  }}

HTTP status code

In Listing 6, checkXMLHttpRequestOfstatusAttribute to check whether the request is successfully completed.statusContains the HTTP status code of the server response. In simple executionGETAndPOSTIn a request, it can be assumed that any code greater than 200 (OK) is incorrect. If the server sends a redirection response (for example, 301 or 302), the browser transparently redirects and obtains resources from a new location;XMLHttpRequestYou cannot see the redirection status code. In addition, the browser automatically addsCache-Control: no-cacheHeader to allXMLHttpRequestIn this way, the Customer Code never needs to process the 304 (unmodified) server response.

Getreadystatehandler ()

getReadyStateHandler()It is relatively complex code, especially if you are not familiar with JavaScript. However, by placing this function in the Javascript library, you can process the Ajax server response without having to process it.XMLHttpRequest. It is important to understand how to use it in your own code.getReadyStateHandler().

As shown in listing 3getReadyStateHandler()Called like this:handlerFunction = getReadyStateHandler(req, updateCart). In this example,getReadyStateHandler()The returned function will checkreqVariableXMLHttpRequestWhether the request has been completed, and then the response XML is called with the nameupdateCart.

Extract shopping cart data

Listing 7 isupdateCart()Code. The function uses Dom to check the XML document of the shopping cart, and then updates the web page (see Listing 1) to reflect the new content of the shopping cart. The focus here is the call to extract data from the xml dom.cartElementgeneratedThe property is inCartA timestamp generated when serialized as XML. Check that the new shopping cart data is not overwritten by the old data. Ajax requests are inherently asynchronous, so this check can handle situations where server responses do not arrive in order.

Listing 7. Update the page to reflect the XML document of the shopping cart

function updateCart(cartXML) { // Get the root "cart" element from the document var cart = cartXML.getElementsByTagName("cart")[0]; // Check that a more recent cart document hasn't been processed // already var generated = cart.getAttribute("generated"); if (generated > lastCartUpdate) {   lastCartUpdate = generated;   // Clear the HTML list used to display the cart contents   var contents = document.getElementById("cart-contents");   contents.innerHTML = "";   // Loop over the items in the cart   var items = cart.getElementsByTagName("item");   for (var I = 0 ; I < items.length ; I++) {     var item = items[I];     // Extract the text nodes from the name and quantity elements     var name = item.getElementsByTagName("name")[0]                                               .firstChild.nodeValue;                                                    var quantity = item.getElementsByTagName("quantity")[0]                                               .firstChild.nodeValue;     // Create and add a list item HTML element for this cart item     var li = document.createElement("li");     li.appendChild(document.createTextNode(name+" x "+quantity));     contents.appendChild(li);   } } // Update the cart's total using the value from the cart document document.getElementById("total").innerHTML =                                           cart.getAttribute("total");}

At this point, the Ajax round-trip process is complete, but you may want the web application to run a program to view the actual effect (see the download section ). This example is very simple and requires many improvements. For example, I include the server-side code for clearing a project from the shopping cart, but cannot access it from the UI. As a good exercise, please try to build code that can implement this function on the existing JavaScript code of the application.


Challenges of Using ajax

Like any technology, Ajax has many possibilities for errors. The problems I have discussed here still lack easy solutions, but they will be improved with the maturity of Ajax. As the developer community increases its experience in developing Ajax applications, it will record best practices and guidelines.

Availability of XMLHttpRequest

One of the biggest problems facing Ajax developers is:XMLHttpRequestHow can I respond when available? Although most modern browsers supportXMLHttpRequestBut there are still a few users of the browser does not support, or the browser security settings prevent the useXMLHttpRequest. If the developed web application is deployed on the enterprise intranet, it may have the right to specify which browser to support.XMLHttpRequestAlways available. However, if you want to deploy it on a public web, you must be careful.XMLHttpRequestAvailable, it may prevent users who use older browsers, private browsers for the disabled, and lightweight browsers on handheld devices from using your applications.

Therefore, you should try to make the application "stable downgrade"XMLHttpRequestSupported browsers can also work. In the example of a shopping cart, the best way to downgrade the application is to have the Add to cart button execute a regular form submission and refresh the page to reflect the status of the updated shopping cart. Ajax actions should be added to the page through javascript when the page is loaded.XMLHttpRequestWhen available, add the Javascript event handler function to each Add to cart button. The other method is to detectXMLHttpRequestWhether it is available, and then provide the Ajax version of the application or a common form-based version.

Availability considerations

Some availability issues about Ajax applications are common. For example, it may be important to let users know that their input has been registered, because the hourglass cursor and the common feedback mechanism of the browser "throbber"XMLHttpRequestNot applicable. One technique is to replace the submit button with information of the "now updating..." type, so that the user will not click the button repeatedly during the waiting for response.

Another problem is that users may not notice that a part of the page they are viewing has been updated. Different visual technologies can be used to bring users' eyes to the update area of the page to alleviate this problem. Other problems caused by Ajax page update include: the "broken" browser's back button, and the URL in the address bar cannot reflect the whole status of the page, hindering the setting of bookmarks. For more information, see the references section for an article dedicated to solving Ajax application availability issues.

Server Load

Replacing the regular form-based UI with Ajax greatly increases the number of requests sent to the server. For example, a common Google Web search has only one request to the server, which appears when the user submits a search form. Google suggest tries to automatically complete the search term. It sends multiple requests to the server when the user inputs them. When developing Ajax applications, pay attention to the number of requests to be sent to the server and the server load caused by this. The method to reduce the server load is to buffer the request on the client and cache the Server Response (if possible ). You should also try to design Ajax web applications to execute as many logic as possible on the client without contacting the server.

Asynchronous Processing

It is very important to understand that it cannot be guaranteed.XMLHttpRequestThe tasks are completed in the order they are assigned. In fact, it should be assumed that they will not be completed in order, and this is taken into consideration when designing the application. In the example of a shopping cart, use the last updated timestamp to ensure that the new shopping cart data is not overwritten by the old data (see listing 7 ). This basic method can be used in shopping cart scenarios, but may not be suitable for other scenarios. Therefore, consider how to handle Asynchronous Server responses during design.


Conclusion

Now you should have a good understanding of the basic principles of Ajax and have a preliminary knowledge of the client and server components involved in Ajax interaction. These are the construction blocks of Java-based Ajax web applications. In addition, you should understand some advanced design issues that accompany the Ajax method. The successful creation of Ajax applications requires the overall consideration, from UI design to JavaScript design, to the server architecture; however, you should now be armed with the core Ajax knowledge required to consider other aspects.

If you are panic by using the technology demonstrated here to compile the complexity of a large Ajax application, there is good news for you. As the development of frameworks such as struts, spring, and hibernate abstracts web application development from the details of the underlying servlet API and JDBC, a toolkit for simplified Ajax development is emerging. Some of them only focus on the client, providing a simple way to add visual effects to the page, or simplifyingXMLHttpRequest. Some of them go further, providing a way to automatically generate an Ajax interface from the server code. These frameworks have completed heavy tasks for you, so you can use more advanced methods for Ajax development. I will study some of them in this series.

The Ajax Community is moving forward rapidly, so there will be a lot of valuable information emerging. Before reading the next phase of this series, I suggest you refer to the articles listed in the references section, especially if you are new to Ajax or client development. You should also spend some time studying the sample source code and consider ways to enhance it.

In the next article in this series, I will discuss it in depth.XMLHttpRequestAPI, and some methods to create XML from Javabean are recommended. I will also introduce how to replace XML for Ajax data transmission, such as JSON (JavaScript Object Notation) Lightweight data exchange format.


Download

Description Name Size Download Method
Sample Code J-ajax1.zip 8 KB HTTP
Information about the Download Method

References

Learning

  • For more information, see the original article on the developerworks global site.

  • "Beyond the Dom" (dethe Elza, developerworks, May 2005): Useful javascript technology for accessing XML documents.
  • "Ajax and Web Service scripting using E4X, Part 2" (Paul Fremantle and Anthony elder, developerworks, November 1st): Use ajax to make soap calls in browsers that support E4X JavaScript extensions.
  • "Ajax: A New Approach to Web Applications" (Jesse James Garret, Adaptive Path, August February 2005): a short article about the origin of Ajax.
  • The Java blueprints solutions catalog: Describes Ajax applications in several common web application scenarios.
  • Ajaxpatterns.org: contains multiple UI technologies for improving Ajax applications.
  • XMLHttpRequest usability guidelines: suggestions for Using ajax to improve user experience.
  • Ajax mistakes: availability issues that AJAX applications should avoid.
  • Java Technology Zone: You can find articles on various aspects of Java programming.

Obtain products and technologies

  • Mozilla Firefox: Dom inspector and JavaScript debugger extensions eliminate a lot of Ajax development pain points.
Related Article

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.