Java development for the Ajax technology

Related Tags:

  I only for learning purposes translation, accurate and complete article please refer to the original! 

  Java development for the Ajax: Construction of dynamic Java applications 

  Ajax laid a better Web application development road 

  Level: Intermediate 

  Philip McCarthy (mailto: philmccarthy@gmail.com? Subject = Build dynamic Java applications), Software Development Consultant, Independent Consultant 

  September 20 2005 

  Heavy pages to a Web application development in the availability of the biggest obstacles for the development of java is also a major challenge.    In this series, the author introduced by Philip McCarthy background-channel approach to create dynamic Web application experience.    Ajax (Asynchronous JavaScript and XML) is a combination of Java technology, XML, and JavaScript programming technology, allows you to build Java technology-based Web applications, the use of pages and break the heavy-duty practice. 

  Ajax, for Asynchronous JavaScript and XML is the use of client-side script and the Web server data exchange Web application development methods.    In this way, interactive Web pages do not have to interrupt the process of re-plus CD, can be dynamically updated.    Using Ajax, you can create closer to a desktop application, direct, high availability, and even richer, more dynamic Web user interface. 

  Ajax is not a technology, it is more like a model - signs and useful design techniques described a method.    For just understand its many developers, it is a new feeling, but all the components to achieve Ajax have existed for many years.    At present the excitement is because, in 2004 and 2005 there have been some very Ajax-based dynamic WebUI, especially Google's GMail and Maps applications, and photo-sharing site Flickr.    These UI full use of a Background channel, but also by some developers as "Web 2.0", and lead to everyone interested in the Ajax applications soared. 

  In this series, I will be all you need is the development of your own Ajax application tools.    In this first article, I will explain the concept behind the Ajax model for Web-based applications to create a system of the Basic steps Ajax interface.    I will use the sample code to demonstrate the realization of Ajax dynamic interface server-side Java code and client JavaScript scripting.    Finally, I would point out that in some ways easy to Ajax mistakes made, as well as in the creation of Ajax application should be considered within the broader context of the availability and easy accessibility of the issues. 

  A better Cart 

  You can use Ajax to strengthen the traditional Web applications through the elimination of pages printed in the interaction to make more fluid.    In order to model it, I will use a simple, can be dynamically updated by adding items to Cart.    With an online store, this method can not wait for the click Heavy pages, and let us continue to browse and select the items to the shopping cart.    Although this code in the cart for example, but the Display can be used other technologies Ajax applications.    Table 1 is shown in the examples Cart used by the html code.    Throughout this article, I will be applied to these HTML code. 

  Table 1: Examples of the relevant Cart code snippet 

  <! - 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: $ 0.00 <span id="total"> </ span> 

  Ajax process 

  An interactive Ajax from a group called XMLHttpRequest JavaScript objects began.    As the name suggests, it allows a client-side scripting to implement HTTP requests, and an XML format will be analytic server response.    Ajax the first step in the process is to create a XMLHttpRequest examples.    Use HTTP methods (GET or POST) to deal with the request, and will target url to the XMLHttpRequest object. 

  Now, remember how Ajax in the first asynchronous processing state?    When you send HTTP requests, you do not want to wait for the browser and server hung response Instead, the pages you wish to continue to respond to users through the interactive interface and the server response to the arrival of the real deal with them.    To complete it, you can XMLHttpRequest register a callback function, and asynchronous request to distribute XMLHttpRequest.    Control immediately be returned to the browser, when the server response arrived, the callback function will be called. 

  In the Java Web server, at the request of any other HttpServletRequest and the same.    Analytical parameters in the request, servlet implementation of the necessary application logic, will respond to the sequence of XML, and write it back to HttpServletResponse. 

  Return to the client, registration XMLHttpRequest the callback function will now be called by the server to handle the return of XML documents.    Finally, the updated user interface to respond to the server from the data transmission, the use of JavaScript to manipulate the pages of HTML DOM.    Ajax Figure 1 is a sequential process map. 

  Figure 1: Ajax process 

  Now, you should be on the Ajax process with a high-level view.    I will enter them every step to see more details of the contents.    If you can not find their positions, they go back a look at the plug, and - because of the asynchronous nature of Ajax method, timing diagrams is not straight forward. 

  Send an XMLHttpRequest 

  I will be the starting point for Ajax timing diagrams began: from the browser to create and send a XMLHttpRequest.    Unfortunately, in different browsers to create XMLHttpRequest method is not the same.    Example 2 List of the JavaScript functions and eliminate these types of browser-related issues, and correctly detected with current methods related to the browser, and can use a return to the XMLHttpRequest.    It will be regarded as the best backup code, it will be a simple copy to your JavaScript library, in the need for a XMLHttpRequest can use it. 

  List 2: cross-browser to create a XMLHttpRequest 

  / * 

  * Return to a new XMLHttpRequest object, if the browser does not support the failure 

  * / 

  Function newXMLHttpRequest () ( 

  Var xmlreq = false; 

  If (window.XMLHttpRequest) ( 

  / / Non-Microsoft browser to create XMLHttpRequest object 

  Xmlreq = new XMLHttpRequest (); 

  ) Else if (window.ActiveXObject) ( 

  / / Create XMLHttpRequest through MS ActiveX 

  Try ( 

  / / Attempt by the new method to create InternetExplorer 

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

  ) Catch (e1) ( 

  / / Create the ActiveX object request failed 

  Try ( 

  / / Attempt by the old method created version InternetExplorer 

  Xmlreq = new ActiveXObject ( "Microsoft.XMLHTTP"); 

  ) Catch (e2) ( 

  / / ActiveX can not create XMLHttpRequest 

  ) 

  ) 

  ) 

  Return xmlreq; 

  ) 

  Later, I will discuss how to deal with do not support the browser XMLHttpReauest some skills.    Now, the list two examples of function in the display will always be able to return to a XMLHttpReauest examples. 

  Back to the example of the cart scenes, as long as users for a directory entries clicking on the Add to Cart button, I would like to call an Ajax interaction.    Called addToCart () function through Ajax onclick call (such as shown in table 1) to update Cart state.    In Table 3, addToCart () the first thing to do is to call newXMLHttpReauest function (such as shown in table 2) to obtain an XMLHttpRequest example, and register a callback function to accept the server response (I explained in detail later, please refer to the list 6). 

  This is because, this request would alter the server status, I will use an HTTP POST to deal with it.    POST data transmission needs through three steps: First, I need to open a communication server resources POST connections - now is an example URL mapping for the server-side cart.do servlet.    Next, set up the first information XMLHttpRequest to mark the contents of the request for the form-encoded.    Finally, the form-encoded data as of the request, and send this request. 

  List 3 in a concentrated display of these steps. 

  Table 3: Send an add to cart XMLHttpRequest 

  / * 

  * Product Code passed in the shopping cart add an entry 

  * ItemCode - need to add entries Product Code 

  * / 

  Function addToCart (itemCode) ( 

  / / Get a XMLHttpRequest examples 

  Var req = newXMLHttpRequest (); 

  / / Set up to receive the request object callback function handle notice 

  Var handlerFunction = getReadyStateHandler (req, updateCart); 

  Req.onreadystatechange = handlerFunction; 

  / / Open a connection to cart the servlet connection HTTP POST 

  / / The third parameter that is asynchronous request 

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

  / / Instructions contained in the request form data 

  Req.setRequestHeader ( "Content-Type." 

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

  / / Send signs need to add to cart in the entry form-encoded data 

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

  ) 

  With the above, you can understand that Ajax to the first part of the process - the client is to create and send HTTP requests.    The next step is to deal with the request of Java Servlet code. 

  Servlet Request Processing 

  Through a servlet to handle and deal with a XMLHttpRequest browser from the ordinary HTTP request basically similar.    HttpServletRequest.getParameter can call () to obtain from POST request from the form of transmission-encoded data.    Ajax request with the ordinary WEB request of this kind have become the same HttpSession part of the process of conversation.    This cart is very Rong example, because we can request the session will be a number of state are kept to the same object JavaBean Cart, and the sequence can be. 

  Table 4 is dealing with Ajax request and update Cart simple servlet code fragment.    Retrieval from the user session in a Cart Bean, in accordance with the parameters of the request to update it.    After Cart Bean to the sequence of XML, and was written to ServletRespone.    Attention, it must respond to the content type is set to application / xml, otherwise, would not be able to respond to XMLHttpRequest content analysis as a XML DOM. 

  Table 4: dealing with the request Ajax code Servlet 

  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)) ( 

  / / Shopping cart add or remove an entry 

  If ( "add." Equals (action)) ( 

  Cart.addItem (item); 

  ) Else if ( "remove." Equals (action)) ( 

  Cart.removeItems (item); 

  ) 

  ) 

  / / Cart sequence of the state to XML 

  String cartXml = cart.toXml (); 

  / / Write XML response. 

  Res.setContentType ( "application / xml"); 

  Res.getWriter (). Write (cartXml); 

  ) 

  Table 5 show a Cart.toXml () method generated XML.    Noting the cart generated elements of nature, is a through System.currentTimeMillis () generated timestamps. 

  Table 5: Cart targeted by the sequence of XML 

  <? 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 look at the download site provides examples of the application source Cart.java, you will see it by simply additional string to generate XML.    For this example, it has been sufficient, I will be in the article, the system introduced after a period of some better ways. 

  Now that you know how to respond to a CartServlet XMLHttpRequest.    The next step is to return to the client, how to respond to the server to update the pages state. 

  Adopted to deal with the server in response to JavaScript 

  XMLHttpRequest the readyState property is a request given the state of the life cycle value figures.    It has said that "not initialize" 0 change to that "complete" 4.    Each readyState change, it will trigger readystatechange, through onreadystatechange attribute configuration callback function will be handling calls. 

  In Table 3, you have to see getReadyStateHandler by calling the function () function to create a handle, and was configured to onreadystatechange property.    GetReadyStateHandler () used to the fact that: JavaScript function is the main target.    This means that the function can be used as parameters to other functions, and you can create and return to other functions.    GetReadystateHandler () is to be done is to return to a function to check whether XMLHttpRequet processing has been completed, and deliver XML server response to the call from the designated processing function.    List 6 is getReadyStateHandler () code. 

  List 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 a monitor XMLHttpRequest examples of anonymous functions 

  Return function () ( 

  / / If the request is the status of "complete" 

  If (req.readyState == 4) ( 

  / / Check whether a server in response to the successful reception 

  If (req.status == 200) ( 

  / / Response information will be made available to deal with the XML transfer function 

  ResponseXmlHandler (req.responseXML); 

  Else () 

  / / HTTP problems 

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

  ) 

  ) 

  ) 

  ) 

  HTTP Status Code 

  In Table 6, the status XMLHttpRequest attributes to be tested to determine whether the request was completed successfully.    When dealing with a simple GET and POST request, you may not think that as long as the 200 (OK), said the state made an error.    If the server sends a redirect response (for example, 301 or 302), the browser will redirect transparent and complete access to the new Position of the corresponding resources; XMLHttpRequest redirect state code will not see.    At the same time, the browser automatically add a cache control: for all XMLHttpRequest use no-cache header, this client code can not handle 304 (not-modified) response. 

  About getReadyStateHandler () 

  GetReadyStateHandler () is a relatively complex piece of code, especially when you do not know when to read JavaScript.    Compromise JavaScript in your library include this function, you can simply deal with Ajax server response, and not pay attention to XMLHttpRequest spent the internal details.    Important is that you have to understand how to use the code getReadyStateHandler (). 

  In Table 3, you see getReadyStateHandler () call like this: 

  HandlerFunction = getReadyStateHandler (req, updateCart). 

  Its return from the function will examine the req variables in the XMLHttpRequest been completed, and call updateCart designated by the callback XML approach to response. 

  Data Extraction Cart 

  List 7 showed updateCart () code.    Use this function to parse Cart DOM XML documents, and updated WEB pages (see table 1) to reflect the new content of the cart.    Attention to the data used to extract the XML DOM calls.    Cart element generated attributes that to generate the sequence of timestamps, by detecting it can guarantee that the data will not be used to cover old new Cart data.    Ajax is asynchronous nature of the request, through the testing process can be effectively avoided, at the server in response to interference. 

  List 7: update page to reflect the content of XML documents Cart 

  Function updateCart (cartXML) ( 

  / / Obtain documents from the root element "cart" 

  Var cart = cartXML.getElementsByTagName (the "cart") [0]; 

  / / Ensure that this document is the latest 

  Var generated = cart.getAttribute ( "generated"); 

  If (generated> lastCartUpdate) ( 

  LastCartUpdate = generated; 

  / / Remove HTML table used to display the contents Cart 

  Var contents = document.getElementById ( "cart-contents"); 

  Contents.innerHTML = ""; 

  / / By entries in the cart recycling 

  Var items = cart.getElementsByTagName ( "item"); 

  For (var I = 0; I <items.length; I + +) ( 

  Var item = items [I]; 

  / / Element name and quantity extracted text node 

  Var name = item.getElementsByTagName ( "name") [0]. FirstChild.nodeValue; 

  Var quantity = item.getElementsByTagName ( "quantity") [0]. FirstChild.nodeValue; 

  / / Create and add entries to the list of HTML 

  Var li = document.createElement ( "li"); 

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

  Contents.appendChild (li); 

  ) 

  ) 

  / / Update the amount of accumulated Cart 

  Document.getElementById ( "total"). InnerHTML = cart.getAttribute ( "total"); 

  ) 

  Now, Ajax process on the end of the tutorial, you may want to use up and running, and how it works (see download).    This example is very simple, has great room for improvement.    For instance, I included in the server-side code from the shopping cart to remove entry code, but the client did not visit the UI in the way.    As an exercise, try on the basis of the existing JavaScript practical this function. 

  The challenge of the use of Ajax 

  Like any technology, the use of Ajax in a considerable number of areas may Fan wrong.    I am here to discuss the issue of the current lack of solutions, with Ajax and will be resolved or the mature and improve.    With Ajax applications development experience in the acquisition, development, the community will be a best practices and guidelines. 

  The effectiveness of XMLHttpRequest 

  Ajax developers face the biggest problem is not with the XMLHttpRequest how to react.    Although most modern browsers support XMLHttpRequest, but there is still a small number of users, they can not support the browser, or because your browser security settings to prevent the use of XMLHttpRequest.    If your Web application published in the internal Intranet, you are likely to be designated to support either browser, and can ensure that the XMLHttpRequest is available.    If you WEB published in the public, you must be aware of the assumption that XMLHttpRequest is available, to stop all the old browser, handheld browser, and so on up to you to use your system. 

  However, you should try to make sure that applications "normal downgrade" used in the system do not apply to reservations support XMLHttpRequest browser functions.    In Cart example, the best way there is a Add to Cart button, can be submitted to the conventional treatment, and refresh page to reflect changes in state Cart.    Ajax line-can be recorded in the pages, through JavaScript added to the page, XMLHttpRequest available only in circumstances for each Add to Cart button with JavaScript handling functions.    Another option is to detect when the user login XMLHttpRequest, a decision to provide Ajax-based version or form to the conventional version. 

  Availability consideration 

  Ajax applications around most of the problems are very common problems.    For example, let users know that their input has been registered and processed, it is very important, because in the process of dealing with XMLHttpRequest can not provide the usual funnel rotation cursor.    A method is to "confirm" button on the text replaced with "being updated…", in order to avoid waiting for the response to users repeatedly click of a button. 

  Another problem is that users may not have noted that they are watching page has been updated.    Can be through the use of various visual skills to attract the customer's perspective to the pages of updating the regional.    There was also a question by Ajax interrupted pages updated browser "Back" button to work, the URL address bar does not reflect all the pages state, and can not use the bookmark function.    See Resource section of the Web site address listed on the article for more on Ajax application usability problems. 

  Server load 

  Use Ajax-based interface instead of the traditional form of the interface may be transmitted to the dramatic increase in the number of server requests.    For example, an ordinary Google search server to create a hit, and the user when search form.    However, Google Suggest, will attempt to automatically complete your search term, users will be unable to send multiple requests to the server.    Ajax in the development of an application, you should note that the number of requests will be sent to end-users, and server load indicators.    You can through the appropriate client cache request, and server load mitigation response to the pressure.    You should also Ajax application in the design of the client to handle more logic, and not with the server-side communications. 

  Asynchronous processing 

  We must remember that there can be no assurance XMLHttpRequest they will be sent in accordance with the order to turn the end.    In fact, you in the design of systems, and others should always assume that they will not be the end of the original order.    In Cart example, the use of a final update the timestamps to ensure that the latest data will not be rewritten.    This is a very basic approach can Cart scenes work, but it may not work in other cases.    In the design of the moment to consider how you deal with asynchronous server response. 

  Conclusion 

  You should now to the fundamental principles of Ajax had a good understanding of the other, you should understand some of the more advanced methods come with the Ajax design problems.    Create a successful Ajax applications require a wide range of methods - from JavaScript UI design to server architecture - but now you should already have a need to use Ajax to the core knowledge. 

  There's good news if you're feeling daunted by the complexity of writing a large Ajax application using the techniques demonstrated here. Just as frameworks like Struts, Spring, and Hibernate have evolved to abstract Web application development away from the low-level details of the Servlet API and JDBC, so toolkits are appearing to ease Ajax development. Some of these focus solely on the client side, providing easy ways to add visual effects to your pages or streamlining the use of XMLHttpRequest. Others go further, providing means to automatically generate Ajax interfaces from server-side code. These frameworks do the heavy lifting for you, so that you can take a more high-level approach to Ajax development. I'll be looking at some of them in this series. 

  The Ajax community is fast moving, and there's a great deal of valuable information out there. Before reading the next installment in this series, I recommend that you consult the articles listed in the Resources section, especially if you're new to Ajax or client - side development. You should also take some time to study the example source code and think about ways to improve it. 

  In the next article in this series, I'll discuss the XMLHttpRequest API in more detail and suggest ways to create XML easily from your JavaBeans. I'll also show you alternatives to XML for Ajax data transfer, such as the JSON (JavaScript Object Notation) lightweight data-interchange format. 

  Download 

  Sample code j-8 KB FTP ajax1.zip 

  Resources 

  Learn 

  "Beyond the DOM" (Dethe Elza, developerWorks, May 2005): Useful JavaScript techniques for XML document access. 

  "Ajax and scripting Web services with E4X" (Paul Fremantle and Anthony Elder, developerWorks, April 2005): Use Ajax to make SOAP calls in browsers that support the E4X JavaScript extension. 

  "Ajax: A New Approach to Web Applications" (Jesse James Garrett, Adaptive Path, February 2005): The seminal essay that gave Ajax its name. 

  The Java BluePrints Solutions Catalog: Documents the application of Ajax to several common Web application scenarios. 

  AjaxPatterns.org: A wiki that includes several UI techniques to improve Ajax applications. 

  XMLHttpRequest Usability Guidelines: Suggestions for using Ajax to enhance user experience. 

  Ajax Mistakes: Usability problems that Ajax applications should avoid. 

  The Java technology zone: Find articles about every aspect of Java programming. 

  Get products and technologies 

  Mozilla Firefox: The DOM Inspector and JavaScript Debugger extension take a lot of the pain out of Ajax development. 

  Discuss 

  Participate in the discussion forum for this content. 

  DeveloperWorks blogs: Get involved in the developerWorks community. 

  About the author 

  Philip McCarthy is software development consultant specializing in Java and Web technologies. He is currently working on Hewlett Packard's Digital Media Platform project at HP Labs, Bristol. In recent years Phil has developed several rich Web clients employing asynchronous server communication and DOM scripting. He is glad we now have a name for them. You can get in touch with Phil at philmccarthy@gmail.com. 




Related articles:

AJAX today without you?
  AJAX today without you?    -- About AJAX applications solved some common problems    It is undeniable that, I am very optimistic about AJAX technology.    I think AJAX technology for the Internet, like the Internet, like HTML.    But at the same time...
Basic knowledge of the application domain
  Basic knowledge of the application domain    First, to explain the term: A record abuzz MX records CNAME records TTL    1, what is abuzz?    Analysis of domain names is domestic or international domain names, as well as Chinese domain names, such as domain na...
Drag movements and movements in detail on collision
  Internet often see in the film, some of the flash can be targeted to drag the mouse.    For example, some similar puzzle the Games, volume control slider, and so on, by the use of flash is the drag-and-drop action.    First, drag a detailed order, first of all, tell us ab...
Flash Mx programming and creative realization: 2D and 3D vector category
  : Cut the Treasury for commercial purposes, only learning and reference    2D vector    / / Vector constructor function    _global.Vector = Function (x, y) (    This.x = x;    This.y = y;    );    / / Vector on the r...
Getting Started Wizard of creating web pages
  Before writing the text first of all, I have to do a certain topic explained.    I am not creating web pages, a master in this respect, there is no ability to write what Guide to such things.    Wrote this guide is only one cavity with their own enthusiasm, will have thei...