Ajax Technology: Building a dynamic Java application

Source: Internet
Author: User
Tags add object end functions numeric value string version java web
Ajax| Program | dynamic
"Guide" in this article, the author Philip McCarthy introduces the experience of creating dynamic Web applications through a background channel approach.

Ajax (asynchronous JavaScript and XML) is a combination of Java technology, XML, and JavaScript programming techniques that allow you to build Java-based Web applications and break the practice of using page overloading.

Ajax, asynchronous JavaScript and XML, is a Web application development method that uses client script to exchange data with a Web server. This way, Web pages can be updated dynamically without interrupting the interactive process. With Ajax, you can create a direct, highly available, richer, more dynamic Web user interface that is close to local desktop applications.

Ajax is not a technology, it's more like a pattern-a way of labeling and describing useful design techniques. It's a new sensation for many developers who just got to know it, but all the components that implement Ajax have existed for many years.

The current buzz is due to the fact that there were some very dynamic WebUI based on Ajax in the 2004 and 2005, especially Google's Gmail and maps apps, and Flickr, a photo-sharing site. These UIs fully use the backend channels, also known as "Web 2.0" by some developers, and have led to a spike in interest in AJAX applications.

A better shopping cart

You can use Ajax to enhance your traditional Web applications by eliminating page loads to make your interactions smoother. In order to demonstrate it, I will use a simple, dynamically updated item to add to the shopping cart. Combined with an online store, this method allows us to continue browsing and picking items into our shopping cart without waiting for the page overload to be clicked.

Although the code in this article is for shopping cart examples, the techniques shown here can be used in other AJAX applications. The HTML code used by the shopping cart sample is shown in Listing 1. In the entire article, I will refer to these HTML code.

Ajax processing Process

An AJAX interaction begins with a JavaScript object called XMLHttpRequest. As the name implies, it allows a client script to execute the HTTP request and will parse an XML-formatted server response. The first step in the AJAX process is to create a XMLHttpRequest instance. Use the HTTP method (get or post) to process the request and set the target URL to the Xmlhttpreques object.

Now, remember how Ajax is first in asynchronous processing? When you send an HTTP request, you don't want the browser to hang up and wait for the server to respond, and instead, you want to continue to interact with the user's interface through the page and process them after the server's response has actually arrived.

To do this, you can register a callback function with XMLHttpRequest and distribute XMLHttpRequest requests asynchronously. Control is immediately returned to the browser, and the callback function is invoked when the server response arrives.

On a Java Web server, the request to arrive is the same as any other httpservletrequest. After parsing the request parameter, the servlet executes the required application logic, serializes the response into the XML, and writes it back to HttpServletResponse.

Back to the client, the callback function registered on the XMLHttpRequest is now invoked to process the XML document returned by the server. Finally, by updating the user interface to respond to server data transfer, use JavaScript to manipulate the HTML DOM of the page. Figure 1 is a sequential diagram of the AJAX processing process.

Figure 1:ajax Processing Process

Now, you should have a high-level view of the AJAX process. I'll go into every step of the way to look at the more detailed content. If you can't find your location, look back at Figure 1, plus-because of the asynchronous nature of the Ajax method, the timeline diagram is not straight forward.

send a XMLHttpRequest

I'll start with the starting point of the Ajax timeline: Create and send a XMLHttpRequest from the browser. Unfortunately, the method of creating XMLHttpRequest in different browsers is not the same. The JavaScript functions of the example in Listing 2 eliminate these browser-related problems, properly detect the methods associated with the current browser, and return a xmlhttprequest that can be used. It's best to look at it as a fallback code and simply copy it to your JavaScript library and use it when you need a xmlhttprequest.

Listing 2: Creating a XMLHttpRequest across browsers

/*

* Returns a new XMLHttpRequest object,

Failure if the browser does not support

*/

function Newxmlhttprequest ()

{

var xmlreq = false;

if (window. XMLHttpRequest)

{

In non-Microsoft browsers

Creating XMLHttpRequest Objects

XMLreq = new XMLHttpRequest ();

else if (window. ActiveXObject)

{

Create XMLHttpRequest through MS ActiveX

try {

Try to create by the new InternetExplorer method

XMLreq = new ActiveXObject

("Msxml2.xmlhttp");

} catch (E1) {

Failed to create the requested ActiveX object

try {

Try to create by the old version of the InternetExplorer method

XMLreq = new ActiveXObject

("Microsoft.XMLHTTP");

} catch (E2) {

Cannot create XMLHttpRequest through ActiveX

}

}

}

return xmlreq;

}

Later, I'll discuss some tips on how to deal with browsers that don't support xmlhttpreauest. Now, the example function shown in Listing 2 will always return a xmlhttpreauest instance.

Back in the shopping cart example scenario, I would invoke an Ajax interaction as long as the user clicked the Add to Cart button for a directory entry. The onclick function named AddToCart () is responsible for updating the status of the shopping cart through an Ajax call, as shown in Listing 1.

In Listing 3, the first thing AddToCart () does is to get an instance of a XMLHttpRequest by calling the Newxmlhttpreauest function (shown in Listing 2) and registering a callback function to accept the server response (which I will explain later in detail, See listing 6).

Listing 3: Send a add to cart XMLHttpRequest

/*

* Add an entry in the shopping cart through the product code

* itemcode– Product code that requires adding entries

*/

function AddToCart (ItemCode)

{

Get a XMLHttpRequest instance

var req = Newxmlhttprequest ();

Sets the handle function used to receive callback notifications from the request object

var handlerfunction =

Getreadystatehandler (req, updatecart);

Req.onreadystatechange =

Handlerfunction;

Open a join to the shopping cart servlet

HTTP Post Join

The third parameter indicates that the request is asynchronous

Req.open ("POST", "cart.do", true);

Indicates that the request body contains form data

Req.setrequestheader ("Content-type",

"application/x-www-form-urlencoded");

Send flag need to add to cart

form-encoded data for the entry in

Req.send ("action=add&item=" +itemcode);

}

With the above, you can learn the first part of the AJAX process-creating and sending HTTP requests on the client side. The next step is the Java servlet code that is used to process the request.

Servlet Request Processing

Handling XMLHttpRequest with a servlet is essentially similar to processing a normal HTTP request from a browser. You can obtain the form-encoded data that is passed by the POST request body by calling Httpservletrequest.getparameter ().

Ajax requests are also part of the same httpsession session process as the normal Web request sample. This is 肜 for the shopping cart example, because we can save the state of multiple requests through a session to the same JavaBean shopping cart object and serialize it.

Listing 4 is a snippet of code that handles AJAX requests and updates a simple servlet for a shopping cart. Retrieves a cart Bean from a user session and updates it with the requested parameters.

The cart Bean is then serialized to XML and is written back to Servletrespone. Note that you must set the type of the response content to Application/xml, otherwise XMLHttpRequest will not be able to resolve the response content to an XML DOM.

Listing 4: servlet code to handle 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 an entry in the shopping cart

if ("Add". Equals (Action))

{

Cart.additem (item);

else if ("Remove". Equals (action)) {

Cart.removeitems (item);

}

}

Serializing the shopping cart status to XML

String cartxml = Cart.toxml ();

Writes XML to response.

Res.setcontenttype ("Application/xml");

Res.getwriter (). write (Cartxml);

}

List 5:cart The XML that the object serializes





Total= "$171.95" >



Hat

2





Chair

1





Dog

1



If you look at the Cart.java in the sample application source provided by the download site, you will see that it generates XML by simply appending strings. For this example, it's enough, and I'll introduce some better methods in the next installment of this system article.

Now you know how Cartservlet responds to a xmlhttprequest. The next step is to return to the client and update the page status with the server response.

Handling server responses through JavaScript

The XMLHttpRequest ReadyState property is a numeric value that gives the status of the request life cycle. It changes from 0 that represents "uninitialized" to 4 that represents "completed." Each time the readystate changes, a ReadyStateChange event is raised, and the callback handler function is invoked through the onReadyStateChange property.

In Listing 3, you have seen a handler function created by calling the function Getreadystatehandler () and configured to the onReadyStateChange property. Getreadystatehandler () uses the fact that a function is the primary object in JavaScript.

This means that functions can be passed as arguments to other functions, and other functions can be created and returned. Getreadystatehandler () to do is to return a function to check whether Xmlhttprequet has finished processing and to pass the XML server to respond to the handler function specified by the caller. Listing 6 is the code for Getreadystatehandler ().

Listing 6: Function Getreadystatehandler ()

/*

* 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) {

Returns an anonymous function that listens for XMLHttpRequest instances

return function ()

{

If the status of the request is "done"

if (req.readystate = 4)

{

Check if the server response was successfully received

if (Req.status = 200)

{

Passing XML containing response information to a handler function

Responsexmlhandler (Req.responsexml);

} else

{

An HTTP problem has occurred

Alert ("HTTP error:" +req.status);

}

}

}

} HTTP status Code

In Listing 6, the Status property of the XMLHttpRequest is tested to determine whether the request completed successfully. When dealing with a simple get and post request, you can assume that an error is indicated as long as it is not a state of (OK). If the server sends a redirect response (for example, 301 or 302), the browser transparently completes the redirection and retrieves the appropriate resource from the new location; XMLHttpRequest will not see the redirection status code.

At the same time, the browser automatically adds a cache control: Use the No-cache header for all XMLHttpRequest so that the client code does not have to process the 304 (not-modified) response.

About Getreadystatehandler ()

Getreadystatehandler () is a relatively complex piece of code, especially if you are not familiar with reading JavaScript. The compromise is to include this function in your JavaScript library, and you can simply handle the AJAX server response without paying attention to the internal details of the XMLHttpRequest. It is important for you to understand how to use Getreadystatehandler () in your code.

In Listing 3, you see that Getreadystatehandler () is called:

handlerfunction=

Getreadystatehandler (Req,updatecart)

The function returned by it checks whether the XMLHttpRequest in the REQ variable has completed and invokes the callback method specified by Updatecart to handle the response XML.

Extract Shopping cart Data

The code in Updatecart () is shown in Listing 7. This function uses the DOM to parse the shopping cart XML document and updates the Web page (see Listing 1) to reflect the new shopping cart content. Note the call to the XML DOM used to extract the data.

The property generated on the cart element, the timestamp generated when serialized, ensures that no old data is overwritten with the new cart data by detecting it. Ajax requests are inherently asynchronous, and this detection can effectively avoid interference with server responses that arrive outside the process.

Listing 7: Updating the page to reflect the contents of the Shopping cart XML document

function Updatecart (cartxml)

{

Get root element "cart" from document

var cart =

Cartxml.getelementsbytagname ("cart") [0];

Make sure this document is up to date

var generated =

Cart.getattribute ("generated");

if (Generated > Lastcartupdate)

{

Lastcartupdate = generated;

Clears the HTML list to display the shopping cart contents

var contents =

document.getElementById ("cart-contents");

contents.innerhtml = "";

Loop through entries in the shopping cart

var items =

Cart.getelementsbytagname ("item");

for (var I = 0;

I < Items.length; i++)

{

var item = Items[i];

Extract a text node 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 to an HTML list for an entry

var li = document.createelement ("Li");

Li.appendchild

(document.createTextNode (name+ "x" +quantity));

Contents.appendchild (LI);

}

}

Update the total amount of the shopping cart

document.getElementById ("Total"). InnerHTML = Cart.getattribute ("Total");

}

The challenge of using Ajax

As with any technology, using AJAX can be a mistake in quite a number of ways. The issues I am discussing here are currently lacking solutions and will be resolved or improved as Ajax matures. With the development of AJAX application experience, the developer community will have the best practice experience and guidelines.

Effectiveness of XMLHttpRequest

One of the biggest problems that Ajax developers face is how to react when XMLHttpRequest is unavailable. Although most modern browsers support XMLHttpRequest, there are a small number of users whose browsers do not support it, or prevent the use of XMLHttpRequest because of browser security settings.

If your Web application is posted on an intranet within your company, you will probably be able to specify which browsers to support and make sure that XMLHttpRequest is available. If you publish on the public Web, you have to realize that by assuming that XMLHttpRequest is available, it prevents users from using your system, such as old browsers, handheld browsers, and so on.

However, you should make every effort to ensure that the application system is "degraded properly" and that the system retains functionality for browsers that do not support XMLHttpRequest. In the shopping cart example, the best way to do this is to have an add to cart button that allows for regular submission and refreshes the page to reflect changes in the status of the cart.

Ajax XMLHttpRequest can be added to the page by JavaScript when the page is loaded, with the JavaScript handler function for each add to cart button only if it is available. Another approach is to detect xmlhttprequest when a user logs on, and then decide whether to provide an AJAX version or a regular form-submitted version.

Usability considerations

Most of the problems surrounding AJAX applications are common problems. For example, it is important for users to know that their input has been registered and processed, because the usual funnel-rotation cursors are not available during XMLHttpRequest processing. One way is to replace the text on the "Confirm" button with the "in update ..." To prevent users from clicking the button more than once while waiting for a response.

Another problem is that users may not notice that the page they are viewing has been updated. You can use a variety of visual techniques to draw the user's vision to the updated area of the page. Another problem is that the AJAX update page interrupts the browser "back to Front" button, the URL in the address bar does not reflect the full state of the page, and cannot use the bookmark function. See the articles on the Web site addresses listed in the resource section to learn more about usability issues with AJAX applications.

Server load

Using an Ajax interface instead of a traditional form-based interface can dramatically increase the number of requests delivered to the server. For example, a common Google search causes a hit to the server and occurs when the user confirms the search form. However, Google suggest will try to automatically complete your search terms and send multiple requests to the server when the user is typing.

When developing an AJAX application, be aware of how many requests you will send to the client side, and the server's load metrics. You can mitigate load pressure by caching requests appropriately on the client and responding to the server. You should also try to process more logic on the client when designing AJAX applications, rather than communicating with the server side.

Processing asynchronous

It's important to remember that nothing can guarantee that XMLHttpRequest will end up in the order in which they are sent. In fact, when you're designing a system, you should always assume that they don't end in the same order. In the shopping cart example, a last-updated timestamp is used to ensure that the latest data is not overwritten.

This very basic approach can work in a shopping cart scenario, but may not work in other situations. At design time consider how you should handle asynchronous server responses.

Conclusion

You should now have a good understanding of the fundamentals of Ajax and, in addition, you should understand some of the more advanced design issues that come with Ajax methods. Creating a successful AJAX application requires a range of approaches-from JavaScript UI design to server-side architecture-but you should now have the AJAX core knowledge you need to use.


<

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.