RIA and Ajax

3,444 views
3,226 views

Published on

This presentation lays out the concept of the traditional web, the improvements web 2.0 have brought about, etc.

I have attempted to explain RIA as well.

The main part of this presentation is centered around ajax, its uses, advantages / disadvantages, framework considerations when using ajax, java-script hijacking, etc.

Hopefully it should be a good read as an intro doc to RIA and Ajax.

Published in: Technology

RIA and Ajax

  1. 1. Introduction to RIA and AJAX Created by - Schubert [email_address]
  2. 2. Agenda <ul><li>RIA (Rich Internet Applications) </li></ul><ul><ul><li>Introduction </li></ul></ul><ul><ul><li>Web 2.0 </li></ul></ul><ul><ul><li>RIA frameworks and toolkits </li></ul></ul><ul><li>Web Orientation </li></ul><ul><ul><li>HTML – DOM – CSS </li></ul></ul><ul><ul><li>HTTP </li></ul></ul><ul><ul><li>XML / JSON </li></ul></ul><ul><li>Ajax </li></ul><ul><ul><li>Introduction </li></ul></ul><ul><ul><li>The XMLHTTPRequest object </li></ul></ul><ul><ul><li>Decoding a simple AJAX application </li></ul></ul><ul><ul><li>DOM Manipulation </li></ul></ul><ul><ul><li>Basic high-level Ajax architecture </li></ul></ul>
  3. 3. <ul><li>Ajax Design Patterns </li></ul><ul><li>Ajax Frameworks and toolkits </li></ul><ul><li>Security and performance related aspects </li></ul><ul><li>Ajax - Advantages and Disadvantages </li></ul><ul><li>Code samples </li></ul><ul><ul><li>Requirements </li></ul></ul><ul><ul><li>Login validation example </li></ul></ul>Agenda – cont’d
  4. 4. RIA – Rich Internet Applications
  5. 5. Introduction - i <ul><li>Page Metaphor </li></ul><ul><li>What exactly is Page Metaphor ? </li></ul><ul><li>The concern on the time lag during a ‘page – turn’ </li></ul><ul><ul><li>Negative brand experience </li></ul></ul><ul><ul><li>Premature use of browser options such as back or refresh </li></ul></ul><ul><ul><li>A user’s clicking again, resulting in further delay </li></ul></ul><ul><ul><li>A user’s giving up and abandoning calls to customer service, entailing costs for the company providing the Web application </li></ul></ul><ul><li>The limitations of the Page Metaphor </li></ul><ul><ul><li>Difficult to manage the display of information in different areas on a page without refreshing the entire page. </li></ul></ul><ul><ul><li>Web applications offer limited capabilities for tracking user interactions. </li></ul></ul>
  6. 6. Introduction – ii Thick Client – Thin Client Server Client Data Data Data Data Business Logic Presentation Logic Presentation Logic Business Logic Business Logic Presentation Logic UI Engine Business Logic Presentation Logic HTML
  7. 7. Introduction - iii The need for smart clients
  8. 8. Introduction - iv RIA Richness Communication Application Bringing the Desktop to the Web ! Connected / Alive Interactive Responsive Traditional web Pervasiveness Online / Offline mode Event’s, notification Security Accessibility A RIA
  9. 9. Web 2.0 - i <ul><li>Where was Web 1.0 ? </li></ul><ul><li>A change in mindset – “Same tools + New ideas” </li></ul>mp3.com Britannica Online personal websites page views publishing content management systems stickiness WEB 1.0 Napster Wikipedia blogging cost per click participation wikis syndication WEB 2.0
  10. 10. Web 2.0 - ii By products
  11. 11. RIA Frameworks and toolkits <ul><li>Java FX </li></ul><ul><li>ADOBE – AIR </li></ul><ul><li>Eclipse – RCP </li></ul><ul><li>Microsoft SilverLight </li></ul><ul><li>OpenLaszlo </li></ul>
  12. 12. Web Orientation
  13. 13. HTML – DOM HTML - Are HTML document structures validated ? - <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;> - What is XHTML ? - HTML 5 and XHTML 5 DOM 
  14. 14. CSS CSS Color – Visibility – Positioning - Backgrounds
  15. 15. HTTP - i OSI (Open Systems Interconnection) – Reference model Application Presentation Session Transport Network Datalink Physical HTTP Headers Methods Status codes
  16. 16. HTTP - ii HTTP headers Request Headers Response Headers <ul><li>Accept </li></ul><ul><li>Accept-Language </li></ul><ul><li>Accept-Encoding </li></ul><ul><li>Content-Type </li></ul><ul><li>Date </li></ul><ul><li>User-Agent </li></ul><ul><li>Cache-Control </li></ul><ul><li>Content-Length </li></ul><ul><li>Content-Disposition </li></ul><ul><li>Content-MD5 </li></ul><ul><li>Content-Type </li></ul><ul><li>Expires </li></ul><ul><li>Last-Modified </li></ul>
  17. 17. HTTP - iii HTTP methods Get - Conditional GET (if headers such as if-modified-since , etc are present.) - Partial GET (if headers include ranges , avoids data transmission already held by the client) POST - Provide a block of data for processing HEAD - Identical to GET except that the server MUST NOT return a message-body in the response. (used for testing hypertext links for validity, accessibility, and recent modification.) PUT / DELETE / TRACE / CONNECT / OPTIONS
  18. 18. HTTP - iv HTTP status codes Informational Success Re - Direction Client Error Server Error 1xx 2xx 3xx 4xx 5xx 100 Continue 200 OK 202 Accepted 301 Moved Permanently 304 Not Modified 400 Bad Request 403 Forbidden 404 Not Found 500 Internal Server Error 502 Bad Gateway 503 Service Unavailable
  19. 19. XML / JSON - i <ul><li>XML </li></ul><ul><ul><li>What is XML? </li></ul></ul><ul><ul><li>DTD’s, Schemas, Namespaces </li></ul></ul><ul><ul><li>XML </li></ul></ul><ul><ul><ul><li>Transformation </li></ul></ul></ul><ul><ul><ul><li>Security </li></ul></ul></ul><ul><ul><li>The Java flavor – (JAXP, JAXB) </li></ul></ul><ul><li>JSON </li></ul><ul><ul><li>What is JSON? </li></ul></ul><ul><ul><li>Use – (Simple Data structures and arrays) </li></ul></ul><ul><ul><li>Advantages </li></ul></ul><ul><ul><li>Disadvantages </li></ul></ul>
  20. 20. XML / JSON - ii {&quot;menu&quot;: { &quot;id&quot;: &quot;file&quot;, &quot;value&quot;: &quot;File&quot;, &quot;popup&quot;: { &quot;menuitem&quot;: [ {&quot;value&quot;: &quot;New&quot;, &quot;onclick&quot;: &quot;CreateNewDoc()&quot;}, {&quot;value&quot;: &quot;Open&quot;, &quot;onclick&quot;: &quot;OpenDoc()&quot;}, {&quot;value&quot;: &quot;Close&quot;, &quot;onclick&quot;: &quot;CloseDoc()&quot;} ] } }} <menu id=&quot;file&quot; value=&quot;File&quot;> <popup> <menuitem value=&quot;New&quot; onclick=&quot;CreateNewDoc()&quot; /> <menuitem value=&quot;Open&quot; onclick=&quot;OpenDoc()&quot; /> <menuitem value=&quot;Close&quot; onclick=&quot;CloseDoc()&quot; /> </popup> </menu> JSON v/s XML
  21. 21. AJAX
  22. 22. Introduction AJAX (Asynchronous JavaScript and XML) Ajax can be defined as a group of interrelated web development techniques used to create interactive web applications or rich Internet applications. AJAX CSS / XHTML DOM XML / XSLT XHR Presentation semantics Dynamic display and data interaction Interchange and manipulation Object for communication
  23. 23. Introduction - i AJAX interactions – classical web model
  24. 24. Introduction - i AJAX interactions – the ajax model
  25. 25. The XMLHTTPRequest object - i The XMLHttpRequest Object specification defines an API that provides scripted client functionality for transferring data between a client and a server. The XMLHttpRequest object implements an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server. Supports any text based format, including XML It can be used to make requests over both HTTP and HTTPS Supports all activity involved with HTTP requests or responses for the defined HTTP methods .
  26. 26. The XMLHTTPRequest object - ii Dependencies <ul><li>DOM – The XHR object spec uses features defined in the DOM specification </li></ul><ul><li>HTTP – Support for the GET, POST, HEAD, PUT, DELETE, OPTIONS </li></ul><ul><li>XML – Support for XML and XMLNamespaces </li></ul>
  27. 27. The XMLHTTPRequest object - iii XHR Object state, events and exceptions XHR Object State UNSENT (Constant value – 0) OPEN (Constant value – 1) SENT (Constant value – 2) LOADING (Constant value – 3) DONE (Constant value – 4) XHR Object Exceptions  XMLHttpRequestException NETWORK_ERR ABORT_ERR XHR Event  readystatechange
  28. 28. The XMLHTTPRequest object - iv XHR Object state - elaborated Unsent When constructed, the XMLHttpRequest object must be in the UNSENT state. This state is represented by the UNSENT constant, whose value is 0. Open The OPEN state is the state of the object when the open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using send(). Sent The SENT state is the state of the object when the user agent successfully acknowledged the request. Loading The LOADING state is the state of the object when all HTTP headers have been received. The object typically remains in this state until the complete message body (if any) has been received. Done The DONE state is the state of the object when either the data transfer has been completed or something went wrong during the transfer.
  29. 29. The XMLHTTPRequest object - v XHR methods open(<method>, <url>) This prepares the XHR object for a call to the server. If you are passing parameters with via GET, you can append them to the URL here. send(<body>) This method actually sends the request to the server.  The body parameter can be used to pass any POST parameters that you would like.  You can format your POST parameters just like a GET query-string setRequestHeader(<header>, <value>) This method allows you to set the specified header with the given value. (e.g. content-type) getAllResponseHeaders() Returns all the response headers as a key / value pair. getResponseHeader(<header>) Returns the specific header requested. abort() Aborts the operation
  30. 30. The XMLHTTPRequest object - vi XHR properties onreadystatechange This property sets the method to be called on every state change.  This is usually your event handler for the asynchronous callback readyState This property defines the state of the XHR.  Possible values include: 0      Uninitated (open() has not been called) 1      Loading (send() has not been called) 2      Loaded (send() has been called, and headers and status are available.) 3      Interactive (Downloading; responseText holds partial data) 4      Complete (Operation is complete) When sending the XHR, you will check to see if the readyState is 0 or 4, and in your asynchronous callback handler, you will check to see if the readyState is 4. responseText This returns the response from the server as a string. (Typically text, JSON)
  31. 31. The XMLHTTPRequest object - vii XHR properties responseXML This returns the response from the server as an XML document.  This is the way to go if you need to return multiple values from your AJAX request. status This returns the HTTP status code from the server such as 200 for OK or 404 for not found. status This returns a string representation of the HTTP status code such as OK for 200 and Not Found for 404
  32. 32. The XMLHTTPRequest object - viii XMLHttpRequest Level 2 <ul><li>Progress Events </li></ul><ul><ul><li>error, abort, load, loadStart, progress, etc. </li></ul></ul><ul><li>Cross site requests </li></ul><ul><li>Handling of byte streams </li></ul>
  33. 33. AJAX code – decoded - i var xmlHttp = GetXmlHttpObject(); if (xmlHttp==null) { alert (&quot;Your browser does not support AJAX!&quot;); return; } var url = “validate.jsp&quot;; url = url + &quot;?id=“ + str; xmlHttp.onreadystatechange = stateChanged; xmlHttp.open(&quot;GET&quot;,url); xmlHttp.send(null); Function to get the XHR object event handler for the asynchronous callback prepare the XHR object for a call to the server Send the request to the server
  34. 34. AJAX code – decoded - ii function stateChanged() { if (xmlHttp.readyState == 4) { if (req.status == 200) { document.getElementById(“validHint&quot;).innerHTML = xmlHttp.responseText; } } } Event handler code
  35. 35. AJAX code – decoded - iii function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;); } catch (e) { xmlHttp=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } } return xmlHttp; } Getting the XHR object Pre 5.5 versions of IE
  36. 36. AJAX code – decoded - iv Code overview
  37. 37. AJAX code – decoded - v UML overview
  38. 38. DOM manipulation concepts var tr = document.createElement('TR'); var td = document.createElement('TD'); tr.appendChild(td); tr.style.backgroundColor = <some color> tr.childNodes tr.firstChild tr.lastChild var parent = td.parentNode; tr.removeChild(td); var img = document.createElement('IMG'); img.setAttribute('src', 'delete.gif'); img.onclick = function() { // function code } Creating elements Adding child elements Setting element properties Referencing child nodes Accessing the parent node Removing parent nodes Assigning behavior to dynamically created elements
  39. 39. Basic high-level ajax architecture
  40. 40. Design Patterns
  41. 41. Design Patterns <ul><li>Foundation Technology Patterns </li></ul><ul><ul><li>Basic Ajax architecture </li></ul></ul><ul><ul><ul><li>How much Richness? </li></ul></ul></ul><ul><ul><ul><li>What are the browser requirements? </li></ul></ul></ul><ul><ul><ul><li>Latency and throughput required </li></ul></ul></ul><ul><ul><li>Display Manipulation – Interacting with the DOM model </li></ul></ul><ul><ul><li>Extension Plugins </li></ul></ul><ul><li>Programming patterns </li></ul><ul><ul><li>Web Services and data formats [REST / RPC / JSON / XML / Strings / HTML] </li></ul></ul><ul><ul><li>Browser server dialog [Call tracking / Periodic refresh] </li></ul></ul><ul><li>Functionality and usability patterns </li></ul><ul><ul><li>Content widgets </li></ul></ul><ul><ul><li>Page architecture [Drag-Drop, etc.] </li></ul></ul><ul><ul><li>Visual Effects </li></ul></ul>
  42. 42. Frameworks and Toolkits
  43. 43. Frameworks and Toolkits - i Google Web Toolkit
  44. 44. Frameworks and Toolkits - ii YUI – Yahoo User Interface
  45. 45. Frameworks and Toolkits - iii jMaki
  46. 46. Frameworks and Toolkits - iv DEMO Google Web Toolkit (GWT) Yahoo User Interface (YUI) extJS
  47. 47. Ajax – Security and Performance related aspects
  48. 48. Security issues - i JavaScript Hijacking JavaScript Hijacking allows an unauthorized attacker to read confidential data from a vulnerable application using a technique similar to the one commonly used to create mash-ups. Traditional Web applications are not vulnerable to JavaScript Hijacking because they do not use JavaScript as a data transport mechanism. <ul><li>JavaScript Hijacking allows an attacker to bypass the Same Origin Policy in the case that a Web application uses JavaScript to communicate confidential information. </li></ul><ul><li>The loophole in the Same Origin Policy is that it allows JavaScript from any website to be included and executed in the context of any other website. </li></ul><ul><li>Even though a malicious site cannot directly examine any data loaded from a vulnerable site on the client, it can still take advantage of this loophole by setting up an environment that allows it to witness the execution of the JavaScript and any relevant side effects it may have. </li></ul><ul><li>JSON arrays are directly vulnerable to JS hijacking as it can stand on their own as a valid JS statements. JS hijacks work on the <script> tag. </li></ul>
  49. 49. Security issues - ii Precautions against JavaScript Hijacking <ul><li>Decline malicious requests </li></ul><ul><li>Prevent direct execution of the JavaScript response </li></ul>The best way to defend against JavaScript Hijacking is to do adopt both defensive tactics.
  50. 50. Security issues - iii Declining Malicious requests <ul><li>Every request should include a parameter that is hard for an attacker to guess. </li></ul><ul><ul><li>One approach is to add the session cookie to the request as a parameter. When the server receives such a request, it can check to be certain the session cookie matches the value in the request parameter. Malicious code does not have access to the session cookie (cookies are also subject to the Same Origin Policy), so there is no easy way for the attacker to craft a request that will pass this test. </li></ul></ul><ul><ul><li>Some frameworks run only on the client side. In other words, they are written entirely in JavaScript and have no knowledge about the workings of the server. This implies that they do not know the name of the session cookie. Even without knowing the name of the session cookie, they can participate in a cookie-based defense by adding all of the cookies to each request to the server. The following JavaScript fragment outlines this &quot;blind client&quot; strategy: </li></ul></ul><ul><ul><ul><li>var httpRequest = new XMLHttpRequest(); </li></ul></ul></ul><ul><ul><ul><li>var cookies=&quot;cookies=&quot;+escape(document.cookie); </li></ul></ul></ul><ul><ul><ul><li>httpRequest.open('POST', url, true); </li></ul></ul></ul><ul><ul><ul><li>httpRequest.send(cookies); </li></ul></ul></ul>
  51. 51. Security issues - iv Preventing direct execution of the Response In order to make it impossible for a malicious site to execute a response that includes JavaScript, the legitimate client application can take advantage of the fact that it is allowed to modify the data it receives before executing it, while a malicious application can only execute it using a <script> tag. When the server serializes an object, it should include a prefix (and potentially a suffix) that makes it impossible to execute the JavaScript using a <script> tag. The legitimate client application can remove this extraneous data before running the JavaScript. Example 1: Prefixing text like while(1) req.open(&quot;GET&quot;, &quot;/object.json&quot;); req.onreadystatechange = function () { if (req.readyState == 4) { var txt = req.responseText; if (txt.substr(0,9) == &quot;while(1);&quot;) { txt = txt.substring(10); } object = eval(&quot;(&quot; + txt + &quot;)&quot;); req = null; } }; Unless the client removes this prefix, evaluating the message will send the JavaScript interpreter into an infinite loop.
  52. 52. Security issues - v Preventing direct execution of the Response Example 2: T he server can include comment characters around the JavaScript that have to be removed before the JavaScript is sent to eval() /* [{&quot;fname&quot;:“Larry&quot;, &quot;lname&quot;:“Ellison&quot;, &quot;phone&quot;:&quot;6502135600&quot;, &quot;purchases&quot;:60000.00, &quot;email&quot;:“larry@oracle.com&quot; } ] */ Unless the client removes these comment characters, the JS code will not be able to be evaluated.
  53. 53. Performance issues - i <ul><li>Array related operations are expensive on all browsers. </li></ul><ul><li>HTML DOM related operations are more expensive than all other operations. </li></ul><ul><li>FireFox specific issues </li></ul><ul><ul><li>“ eval” of object or function: These two operations take Safari 9.4us and 22.7us, IE7 172us and 94us. But they take FireFox 546us and 749us. </li></ul></ul><ul><ul><li>Object creation is more expensive compared to any other browser. </li></ul></ul><ul><li>IE specific issues : Mainly string manipulation features </li></ul>
  54. 54. Performance issues - ii What would we like to monitor ? <ul><li>The number of HTTP requests an application makes </li></ul><ul><li>Track I/O disk issues </li></ul><ul><li>Analyze network traffic </li></ul><ul><li>Discover excessive calls </li></ul><ul><li>Reduce memory consumption </li></ul><ul><li>Solve other performance problems </li></ul><ul><li>Apache Bench : Simulates a load on a server </li></ul><ul><li>Tsung : Tests multi-protocol loads </li></ul><ul><li>Bonnie++ : Tracks down I/O disk issues </li></ul><ul><li>Wireshark : Analyzes network traffic </li></ul><ul><li>Comet server application tools : Used for longer-lived connections, higher volumes of concurrency, lower latency, and lower server load </li></ul><ul><li>FireFox plugins (e.g. FireBug) </li></ul>
  55. 55. Ajax – Advantages & Disadvantages
  56. 56. Advantages <ul><li>Makes use of existing technologies which are proven. </li></ul><ul><li>Support for mature tools and processes. </li></ul><ul><li>Acceptance by industry leaders. </li></ul><ul><li>Killer apps already available, hence technology buy-in appeals to most organizations. </li></ul><ul><li>Reduction in bandwidth and load time. </li></ul><ul><li>Allows for a richer user experience as Ajax has proved to provide the glue required for Web 2.0 application models. </li></ul><ul><li>Existing websites can easily scale up to be ajax driven with little effort. </li></ul><ul><li>Platform neutral. </li></ul>
  57. 57. Disadvantages <ul><li>The need for Java script to execute ! </li></ul><ul><li>The ‘back button’ mentality – need for additional care. </li></ul><ul><li>Dynamic pages driven by an ajax architecture backed mash-up style make it difficult to bookmark a particular state of the application. </li></ul><ul><li>Search engine indexing issues with dynamic data. – How can engines find dynamic content ? </li></ul><ul><li>Current policies enforce using a single domain which may act as a deterrent to mash-up based applications which have data and content on various domain sites. </li></ul><ul><li>No widely adopted best practice standards to test Ajax apps. Testing tools do not fully understand the Ajax model (even/data). </li></ul><ul><li>Vulnerable to attack if not fully tested. </li></ul>
  58. 58. Code Samples
  59. 59. Requirements <ul><li>Servlet Container </li></ul><ul><li>Database </li></ul><ul><li>JDBC Driver for the dB used. </li></ul><ul><li>Editor </li></ul>
  60. 60. Code sample for a Login request <jsp> login.jsp Accept user credentials Login-ajax.js <jsp> validatelogin.jsp JDBC Database 1 2 3 4 5 6 Success / Failure 7 Behind the Scenes – using fire bug
  61. 61. Disclaimer <ul><li>No Representation </li></ul><ul><ul><li>This presentation has been compiled in good faith and no representation of either materials / references are made or warranty given (either express or implied) as to the completeness or accuracy of the information it contains. </li></ul></ul><ul><li>Logos & trademarks used in this presentation belong to their respective owners. </li></ul>

×