Top Banner
Web 2.0 and Java: RIA and AJAX Sridhar Reddy Technology Evangelist Sun Microsystems, Inc.
55

Web 2.0 and Java: RIA and AJAX

Jan 21, 2015

Download

Documents

Sampetruda

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 1. Web 2.0 and Java:RIA and AJAXSridhar Reddy Technology Evangelist Sun Microsystems, Inc.

2. Goal Learn how to architect and build rich web applications using AJAX 3. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo and Tutorial Blueprints AJAX Usecases Summary 4. Web 2.0 Principles Web as a Platform Data is key and should be shared Software is constantly evolving Lightweight Programming Models > SOAP/REST Rich User Experience > AJAX 5. Web 1.0 Web 1.5Web 2.0 Personal Websites Wikis Blogging - Roller Email/News Groups Discussion Forums RSS Syndication Popups Popunders Google Ads Web Directories Yahoo HousingMaps.com Web Classifieds Cragislist Google Maps Terraserver MapQuest iTunes mp3 Napster 6. What Makes the Web 2.0 Different? Personalized User oriented Easy to Use Get you to the information you want Useful 7. Mashups? Housingmaps.com 8. Rich User Experience Take a look at a typical desktop application (Spreadsheet, email app, etc.) The program responses intuitively and quickly The program gives a user meaningful feedback's instantly > The cursor changed shape > Icons light up as mouse hovers them > Selected text changes color Things happen naturally > I don't have to click a button or a link 9. Characteristics of Conventional Web Application Click, wait, and refresh user interaction Page refreshes from the server needed for all events, data submissions, and navigation The user has to wait for the response Synchronous request/response communication model Page-driven Workflow is defined in the server 10. Issues of Conventional Web Application Slow response Loss of operational context during refresh No instant feedback's to user activities > A user has to wait for the next page Excessive server load and bandwidth consumptionThese are the reasons why Rich Internet Application(RIA) technologies were born. 11. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo and Tutorial Blueprints AJAX Usecases Summary 12. Rich Internet Application (RIA) Technologies Applet Macromedia Flash Java WebStart DHTML DHTML with IFrame AJAX 13. Macromedia Flash Designed for playing interactive movies Programmed with ActionScript Implementation examples > Macromedia Flex > Laszlo suite (open source) Pros: > Good for vector graphics Cons: > Browser needs a Flash plug-in > ActionScript is proprietary and hard to debug 14. Java WebStart Desktop application delivered over the net > Leverages the strengths of desktop apps and applet Pros > Desktop experience once loaded > Leverages Java technology to its fullest extent > Disconnected operation is possible > Application can be digitally signed Cons > Old JRE-based system do not work > First-time download time could be still significant 15. DHTML (Dynamic HTML) DHTML = JavaScript + DOM + CSS Used for creating interactive applications No asynchronous communication, however > Full page refresh still required > Reason why it has only a limited success 16. DHTML with IFrame IFrame was introduced as a programmable layout to a web page > An IFrame is represented as an element of a DOM tree > You can move it, resize it, even hide it while the page isvisible An invisible IFrame can add asynchronous behavior > The visible user experience is uninterrupted operationalcontext is not lost It is still a hack 17. AJAX DHTML plus Asynchronous communication capability through XMLHttpRequest Pros > Most viable RIA technology so far > Tremendous industry momentum > Several toolkits and frameworks are emerging Cons > Still browser incompatibility > JavaScript is hard to maintain and debug JSF/AJAX Integration will help 18. Real-Life Examples of AJAX Apps Google maps > http://maps.google.com/ Goolgle Suggest > http://www.google.com/webhp?complete=1&hl=en Gmail > http://gmail.com/ A9.com - Amazon.com search > http://a9.com/ Many more are popping everywhere 19. AJAX: Demo Google Maps, Yahoo Maps New, A9.com 20. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo and Tutorial Blueprints AJAX Usecases Summary 21. What is AJAX AJAX is an ancronym 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 apps: > Reduce server load > Dramatic improvement in user interface > Reduced load on browser/script 22. User Interface: Traditional Web vs. AJAX 23. Components: Traditional Web vs. AJAX 24. Examples of AJAX apps 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 25. AJAX Application Real time form data validation Auto-completion Master details operations Sophisticated user interface control > Tree controls, Tables, menus, progress bars ... Refreshing Data on the Page > game scores, exchange rates, interest rates etc. Server side notification > simulate a server-side push by polling the server 26. 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 content type > Setting this to text/xml with make your life easier in almost all implementations 27. XMLHttpRequest Communication may be GET/POST Does not show the user anythingno 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 28. XMLHttpRequest Methods open(method, URL, syn/asyn) > Assigns destination URL, method, mode 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 29. 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 30. IFRAME IFRAME is a mini-browser window in an HTML document Can be hidden (0 width, 0 height) IFRAME can call a URL Javascript can read the contents of the IFRAME User sees messages on status bar Hears a click as server submits request Much slower than XMLHTTPRequest 31. Anatomy of an AJAX Request 32. Steps of An AJAX Interaction 1. A client event occurs 2. An XMLHttpRequest object is created and configured 3. The XMLHttpRequest object makes a call 4. The request is processed by the ValidateServlet 5. The ValidateServlet returns an XML documentcontaining the result 6. The XMLHttpRequest object calls the callback()function and processes the result 7. The HTML DOM is updated 33. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo Sun Java Studio Creator Blueprints AJAX Usecases Summary 34. Demos and Tutorials Google Blueprints solutions in NetBeans > Servlet and JSF Tutorials Create a AJAX enabled JSF components using Sun Java Studio Creator 35. AutoComplete Using a Servlet Create a search field in an HTML page that is capable of providing potential completions of employee names as the user types in characters. Having auto-completion in the page would save the user the need to navigate back and forth between two pages to find a specific employee. 36. index.jsp Page Auto-Complete Form 37. AutoComplete Event Handler function doCompletion() { if (completeField.value == "") { clearTable(); } else { var url = "autocomplete?action=complete&id=" + escape(completeField.value); var req = initRequest(url); req.onreadystatechange = function() {if (req.readyState == 4) { /* Request processing complete */if (req.status == 200) { /* http: success */parseMessages(req.responseXML);} else if (req.status == 204){ clearTable(); }} }; req.open("GET", url, true); req.send(null); } 38. AutoComplete XMLHttpRequest function initRequest(url) { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; return new ActiveXObject("Microsoft.XMLHTTP"); } } 39. AutoComplete parseMessages function parseMessages(responseXML) {clearTable();var employees = responseXML.getElementsByTagName("employees")[0];if (employees.childNodes.length > 0) {completeTable.setAttribute("bordercolor", "black");completeTable.setAttribute("border", "1");} else {clearTable();}for (loop = 0; loop < employees.childNodes.length; loop++) {var employee = employees.childNodes[loop];var firstName = employee.getElementsByTagName("firstName")[0];var lastName = employee.getElementsByTagName("lastName")[0];var employeeId = employee.getElementsByTagName("id")[0];appendEmployee(firstName.childNodes[0].nodeValue, lastName.childNodes[0].nodeValue, employeeId.childNodes[0]. nodeValue); } 40. AutoComplete Servlet doGet() public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {...String targetId = request.getParameter("id");Iterator it = employees.keySet().iterator();while (it.hasNext()) {EmployeeBean e = (EmployeeBean)employees.get((String)it.next());if ((e.getFirstName().toLowerCase().startsWith(targetId) ||e.getLastName().toLowerCase().startsWith(targetId)) && !targetId.equals("")) {sb.append("");sb.append("" + e.getId() + "");sb.append("" + e.getFirstName() + "");sb.append("" + e.getLastName() + "");sb.append("");namesAdded = true;}}if (namesAdded) {response.setContentType("text/xml");response.setHeader("Cache-Control", "no-cache");response.getWriter().write("" + sb.toString() + "");} else {response.setStatus(HttpServletResponse.SC_NO_CONTENT);} 41. AutoComplete Update 42. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo Blueprints AJAX Usecases Summary 43. Blueprints - Usecases for AJAX Refreshing data Real-time Validation Auto-Complete Advanced GUI widgets and controls 44. Refreshing Data With AJAX How do you push update data from a server-side application to an HTML page? 45. Realtime Validation Using AJAXHow do I use AJAX to use server-side validation logicwithout page refresh? 46. Auto-Complete How can you provide a better means of navigating a large set of data based on a search query? 47. Auto-Complete with Java Server Faces Component 48. AgendaWeb 2.0 Rich Internet Applications (RIA) Technologies What Is AJAX? Demo Blueprints AJAX Usecases Summary 49. Reasons for using Client-side JavaScript Libraries Provides higher abstraction APIs > Easier to develop AJAX applications Handles browser incompatibilities > No need to reinvent the wheel Handles graceful degradation > Uses IFrame if the browser does not support XMLHttpRequest Handles various UI issues > Back and forward buttons > Bookmarking 50. Client-side JavaScript Libraries DOJO Toolkit > http://dojotoolkit.com/ Prototype > http://prototype.conio.net/ Many more are emerging 51. Server-side Frameworks Two types > The server generates JavaScript code dynamically > Component-based model> JSF components can hide the complexity of AJAXprogramming completely Examples > DWR (Dynamic Web Remoting)> http://dwr.dev.java.net/ 52. AJAX Futures AJAX-enabled JSF Component libraries Standardization of XMLHttpRequest More best practices in the programming model Better browser support Framework support and new frameworks 53. Summary AJAX helps make applications more interactive Java provides the ideal platform for AJAX apps Follow the guidelines Use AJAX where it makes sense. > Simple Servlets Require more work > JSF Components Provide End to End Support The BluePrints team and BluePrints Solutions Catalog is a great AJAX resources 54. Resources BluePrints AJAX Page: > http://java.sun.com/blueprints/ajax.html AJAX FAQ for the Java Developer > http://blueprints.dev.java.net/ajax-faq.html The BluePrints Solutions catalog on AJAX: https://bpcatalog.dev.java.net/nonav/solutions.html Greg Murray's blog: AJAX Solutions Online > http://weblogs.java.net/blog/gmurray71/ 55. Web 2.0 and Java:RIA and AJAXSridhar Reddy [email protected] Sun Microsystems, Inc.