Your SlideShare is downloading. ×
AJAX: Riding the Browser Based Horse a Little Further
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

AJAX: Riding the Browser Based Horse a Little Further

970

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
970
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Web 2.0 and Java: Rich Internet Applications and AJAX Lee Chuk Munn Staff Engineer Sun Microsystems, Inc.
  • 2. Goal Learn how to architect and build rich web applications using ™ AJAX and J2EE technologies.
  • 3. Agenda • Architecture • XMLHttpRequest Object • User Interface • Server Side • Example of AJAX Use Cases • Considerations and Gotchas • AJAX Applications and the Java EE Platform • Summary
  • 4. Conventional Rich Web Applications • Page refreshes needed for all events, data submissions, and navigation • Plugins, applets, or browser black magic • Have varying support for JavaScript™ technology and CSS • Use the least common denominator of technologies
  • 5. New Wave of Web Application • Google maps http://maps.google.com/ • Gmail http://gmail.com/ • Google Suggest http://www.google.com/webhp?complete=1&hl=en • ZUGGEST- an XMLHttp Experiment using Amazon http://www.francisshanahan.com/zuggest.aspx
  • 6. What is AJAX? • AJAX is an acronym for Asynchronous Javascript And XML > AJAX uses JavaScript combined with xml to grab information from a server without refreshing the page > nothing new, the main requirement is the web browser has the support for XMLHttpRequest object > The term AJAX was coined Jesse James Garrett in February 2005 • Advantages on web applications: > Reduce server load (sometimes) > Dramatic improvement in user interface
  • 7. Architecture
  • 8. Traditional Web
  • 9. AJAX
  • 10. Anatomy of an AJAX Request Realtime update
  • 11. Major Components AJAX • Javascript > JavaScript in a page is called when an event in a page occurs • DOM > API for accessing and manipulating structured documents > Represent the structure of XML and HTML documents • CSS > CSS allow for a clear separation of the presentation from the content and may be changed programatically by JavaScrip • HTTP > XMLHttpRequest
  • 12. Examples of AJAX Use Cases • Real time form data validation • Auto-completion • Master details operations • Sophisticated user interface control • Server side notification
  • 13. The XMLHttpRequest Object
  • 14. XMLHttpRequest • Communication may be GET/POST • Does not show the user anything—no status messages • Documents must be text/xml • Page continues to process events, the XMLHttpRequest object works in the background • Limited Number of requests allowed • Allows you to specify a handler method for state changes • Handler notified when request is: > Initialized, Started, In the process of being returned, Completely finished
  • 15. XmlHttpRequest • Creating an XmlHttpRequest instance > Many/most aspects of using this object have been standardized > Creating the object, however, is browser specific • Asynchronous requests > Utilize a combination of the onreadystatechange function and status-properties to ensure processing occurs when server processing is complete • Response > The content must be set to text/xml > Should turn off caching
  • 16. XMLHttpRequest Methods • open(“method”, “URL”, sync/async) > Assigns destination URL, method, mode > sync = false, async = true • send(content) > Sends request including string or DOM object data • abort() > Terminates current request • getAllResponseHeaders() > Returns headers (labels + values) as a string • getResponseHeader(“header”) > Returns value of a given header • setRequestHeader(“label”,”value”) > Sets Request Headers before sending
  • 17. XMLHttpRequest Properties • onreadystatechange > Event handler that fires at each state change > You implement your own function that handles this • readyState – current status of request > 0 = uninitialized > 1 = loading > 2 = loaded > 3 = interactive (some data has been returned) > 4 = complete • status > HTTP Status returned from server: 200 = OK • responseText > String version of data returned from server • responseXML > XML DOM document of data returned • statusText > Status text returned from server
  • 18. Instantiating XMLHttpRequest 01 var req; 02 //Non IE browser 03 if (window.XMLHttpRequest) { 04 req = new XMLHttpRequest(); 05 else if (window.ActiveXObject) { 06 req = new ActiveXObject(“Microsoft.XMLHTTP”); 07 } else { 08 alert(“Your browser is not currently supported”); 09 return; 10 } 11 //Use GET to send data asynchronously 12 req.open(“GET”, url, true); 13 //Set the callback function 14 req.onreadystatechange = callback; 15 //Send the request 16 req.send(null);
  • 19. Synchronous vs. Asynchronous • Synchronous mode (not AJAX application) > req.open('GET', 'url' , false) > Can be used to retrieve data and update selected parts of the page without refreshing the entire page > if there is nothing useful for the user to do after a request is submitted to a server > Block the user interface • Asynchronous mode (AJAX application) > req.open('GET', 'url', true) > Get a callback when the data has been received > Browser continue to work as normal while requests are processed in the background > Example: Pan a google map as fast as you can and realize the page itself never reloads
  • 20. Synchronous vs. Asynchronous • Requests can be made asynchronously or synchronously > both techniques allow web page to be updated without refreshing it > anything useful the user can do while processing request? > if yes then use asynchronous, otherwise use synchronous • Most frameworks support either • Asynchronous is typically recommended • Synchronous requests may freeze the browser for the duration of the request
  • 21. The User Interface
  • 22. Elements in a AJAX Web Page • Figure out the use case > Eg. Realtime validation of user login • Decide on the JavaScript event you which to intercept > Eg. onKeyUp, onMouseOver, onLoad, onSubmit • Set a function to intercept this event • Define a callback function • Set aside an area to display the result
  • 23. Example: User Validation 01 <head> 02 <script type=”text/javascript”> 03 function validateUserId( ) { 04 //do something here 05 } 06 function processCallback( ) { 07 //do something here 08 } 09 </script> 10 </head> 11 <body> 12 <input type="text" size="20" id="userId" name="id" 13 onkeyup="validateUserId( )"> 14 15 <div id=”message”></div> 16 </body>
  • 24. Sending Request • Decide if operation is synchronous or asynchronous • Decide if HTTP method is GET or POST > Slight coding difference • For asynchronous request > Set callback function > Dispatch method needs to be thread-safe due to network latency • Encode the data before sending to server
  • 25. Example: Dispatch Function – GET 01 function validateUserId( ) { 02 //Get an instance of XMLHttpRequest 03 var req = //get a XMLHttpRequest object 04 //Get the user id 05 var user = document.getElementById(“userId”); 06 //Construct the URL 07 var url = “validate?id=” + escape(user.value); 08 //Set the callback 09 req.onreadystate = processCallback; 10 //Send the request 11 req.open(“GET”, url, true); 12 req.send(null); 13 }
  • 26. Example: Dispatch Function – POST 01 function validateUserId( ) { 02 //Get an instance of XMLHttpRequest 03 var req = //get a XMLHttpRequest object 04 //Get the user id 05 var user = document.getElementById(“userId”); 06 //Construct the URL 07 var url = “validate”; 08 //Set the callback 09 req.onreadystate = processCallback; 10 //Send the request 11 req.open(“POST”, url, true); 12 req.setRequestHeader(“Content-Type” 13 , “application/x-www-form-urlencoded”); 14 req.send(“id=” + escape(user.value)); 15 }
  • 27. Example: Callback Function 01 function processCallback( ) { 02 //Check if the request has completed 03 if (req.readyState != 4) 04 return; 05 //Check if the status is okay <message> 06 if (req.status != 200) { valid / invalid 07 alert(“Error!”); </message> 08 return; 09 } 10 //Extract the result from the return XML document 11 var result = req.responseXML 12 .getElementByTagName(“message”)[0]; 13 var msg = result.childNodes[0].nodeValue; 14 displayMessage(msg); 15 }
  • 28. Example: Displaying the Result Update the HTML's DOM 01 function displayMessage(msgText) { 02 var msgElement = 03 document.getElementById(“message”); 04 var text; 05 if (msgText == valid) { 06 msgElement.style.color = “green”; 07 text = document.createTextNode(“Valid user id”); 08 } else { 09 msgElement.style.color = “red”; 10 text = document.createTextNode(“Invalid user id”); 11 } 12 msgElement.replaceChild( 13 text, msgElement..childNodes[0]); 14 }
  • 29. The Server's Side
  • 30. Server Side AJAX Processing • Request are either in HTTP GET or POST • Use Servlet programming model to handle these request • Things to keep in mind > Responses must be encoded in 'text/xml' > Data must be in XML format > Request to Servlet may be more frequent and granular > Eg. each keystroked is processed in real time validation > Turn off caching
  • 31. Example: AJAX Server Processing 01 public void doGet(HttpServletRequest req 02 , HttpServletResponse res) 03 throws IOException, ServletException { 04 05 //Extract the parameter and check if we have a valid ID 06 String id = req.getParameter(“id”); 07 String valid = checkId(id); 08 09 //Encode the response as “text/xml” 10 res.setContent(“text/xml”); 11 //Request the browser not to cache the results 12 res.setHeader(“Cache-Control”, “no-cache”); 13 //Write the result 14 res.getWriter().write(valid); 15 }
  • 32. Considerations and Gotchas
  • 33. Things to Consider • AJAX requires you to think about interface and interaction > Usability is the key—and is what you should strive for > Do not break what the user is focusing on > Make sure to give the user feedback > Do not over-use it • How do you handle state + sessions? > Decision on where to put state information gets trickier > Can all be on the client so you can have truly stateless servers > Requires a lot more client code for state – server already has mechanism for clustered > State synchronization > What happens if the server or network dies?
  • 34. Things to Consider (cont.) • Navigation Issues > Back button is meaningless unless you code ‘undo’ functionality to it > Invisible IFRAME and puts results back to visible web page > Google Maps, Dojo toolkit (http://dojotoolkit.org) > Bookmarking doesn’t work unless you manually change the URL > Explicitly create link for bookmarking eg. GoogleMap > Refresh button can kill your app > Save state in <body onload> method • Don’t assume the server is going to respond instantly > Network latency – consider interval between user request and server response > Need visual feedback for background activity > Preload data on the server where possible
  • 35. AJAX Efficiency • Keep requests as concise as possible • Only request/respond with the data required • Preload data on the server where possible • Put some thought into what event will trigger • Some events happen faster than is practical to make server requests > i.e. Although Google Suggest appears to make a request on each keystroke, closer examination reveals it is actually makes requests at regular time intervals
  • 36. Things You May not Like • Big problems could easily arise from a user disabling JavaScript in their browsers! • There will be some learning curve > You may not already be doing it • Browser differences - not completely standardized • Not yet official part of any spec • Debugging - Java code on server mixes with JavaScript on the client • Viewable source > Potential security issues > Reverse engineering
  • 37. Java Server Faces and AJAX
  • 38. JavaServer Faces: What is it? • A server-side user interface component framework TM for Java technology-based web applications > Components > Events > Validators > Back-end-data integration > Designed to be added to tools
  • 39. JSF Architecture Server Request UI Client (events) Response (markup)
  • 40. Architecture: Dependencies JSF App JSF App JSF Tags JSP JSF API (1.2 or later) Servlets (2.3 or later)
  • 41. Sample JSF Page TM 1: <%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> 2: <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> 3: <f:view> 4: <h:form formName=”logonForm”> 5: <h:panelGrid columns=”2”> 6: <h:outputText value=”Username:”/> 7: <h:inputText id=”username” length=”16” 8: value=”#{LoginFormBean.userName}”/> 9: 10: <h:commandButton type=”submit” 11: label=”Log On” 12: action=”success”/> 13: <h:commandButton type=”reset” 14: label=”Reset”/> 15: </h:panelGrid> 16: </h:form> 17: </f:view>
  • 42. JSF Component Approach • Using “AJAX-enabled” JavaServer Faces components to construct the user interface > Control Content Rendering > Control of Server Side Logic > All in one component > Reusable > Usable in a tool > Hide AJAX complexity from page developers
  • 43. AJAXing JSF Components <h:outputText value="Name:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.name}" /> <h:outputText value="Street:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.street}" /> <h:outputText value="City:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.city}" /> <h:outputText value="State:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.state}" /> <h:outputText value="Zip:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.zip}" />
  • 44. AJAX Enabled JSF Components
  • 45. AjaxPhaseListener Render generates: <script type="text/javascript" src="faces/ajax-textfield.js"> script request: write out JavaScript to be included in JSP public void afterPhase(PhaseEvent event) { String rootId = event.getFacesContext().getViewRoot().getViewId(); if (rootId.endsWith(SCRIPT_VIEW_ID)) { handleResourceRequest(event, "script.js","text/javascript"); } else if (rootId.endsWith(CSS_VIEW_ID)) { handleResourceRequest(event, "styles.css", "text/css"); } else if (rootId.indexOf(AJAX_VIEW_ID) != -1) { handleAjaxRequest(event); } }
  • 46. jMaki Project • Wrapping AJAX in JavaServer Faces > Using JSF components or JSF tags > Hides AJAX complexity from developer • Currently supports components from > Dojo, Script.aculo.us, Yahoo UI Widgets, Spry DHTML Goodies and Google • Allows mix and match web components easily • Developers can create new jMaki components • NetBeans plugin • https://ajax.dev.java.net
  • 47. Summary
  • 48. Summary • AJAX programming style helps makes web application more interactive • Inherent problems with AJAX > Network latency, JavaScript support, browser issues, etc. • JavaEE is a great platform for delivering AJAX applications > Only have to redevelop the client > Future versions of web technology will have tighter support for AJAX • Start small and don't over do it
  • 49. Thank You Questions?

×