Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ajax. AJAX zAsynchronous Javascript and XML zLa page n’est pas rechargée yRafraîchissement partiel yLa page web est traitée comme un template zAsynchrone.

Similar presentations


Presentation on theme: "Ajax. AJAX zAsynchronous Javascript and XML zLa page n’est pas rechargée yRafraîchissement partiel yLa page web est traitée comme un template zAsynchrone."— Presentation transcript:

1 Ajax

2 AJAX zAsynchronous Javascript and XML zLa page n’est pas rechargée yRafraîchissement partiel yLa page web est traitée comme un template zAsynchrone yLe client peut continuer à interagir en attente de la réponse zUtilisation yValidation par le serveur des données d’un formulaire en temps réel yAuto-complétion yPréchargement à la demande. yContrôles et effets sophistiquées dans les interfaces usager sans rechargement des pages x progress bar, calendriers, arbres… yRafraîchissement des données et mode « push » par le serveur ySoumission partielle sans rechargement de la page: listes de formulaires dépendants. yMashups xobtenir et intégrer des données provenant de plusieurs sources. yPage == application qui s’approche d’une application desktop.

3 Technologies utilisées par Ajax zCascading Style Sheets (CSS) yUn langage de balises pour définir le style de présentation d’une page, e.g. polices, couleurs.... zJavaScript yÉlément clé : l’objet XMLHttpRequest utilisé pour échanger des données entre le client web et le serveur web zDocument Object Model (DOM) yFournit une vue logique de la page web sous forme d’arbre zXML yFormat d’échange de données entre le serveur web et le client xD’autres formats peuvent aussi être utilisés Par exemple, HTML, JavaScript Object Notation (JSON), ou texte simple.

4 Fonctionnement

5 Ajax et Javascript

6 zLes différents états d’une requête

7 Les propriétés d’une requête XMLHttpRequest

8 Les méthodes d’une requête XMLHttpRequest

9 Construction et envoi d’une requête Post

10 Ajax et Java

11 Quelle stratégie de développement adopter ? z Design Strategy 1: Do It Yourself zDesign Strategy 2: Use a Client-Side JavaScript Technology Library zDesign Strategy 3: Use a Client-Server Framework zDesign Strategy 4: Do the Wrap Thing zDesign Strategy 5: Go Remote zDesign Strategy 6: Go All Java Technology

12 Design Strategy 1: Do It Yourself zClient yÉcrire soi-même le code en xJavaScript, xCSS, xDOM, xPrésentation de la page. zServeur yCoder explicitement la gestion de l’appel XMLHttpRequest yRendre une réponse appropriée xPar exemple en XML

13 Exemple zImplémenter une bulle pop-up

14 Etapes à réaliser 1.Associer l’événement à une fonction JavaScript. 2.Créer et configurer un objet XMLHttpRequest. 3.Faire une requête au serveur à travers l’objet XMLHttpRequest. 4.Traiter la requête sur le serveur et rendre un document XML qui contient le résultat. 5.Traiter le résultat par la fonction JavaScript de callback(). 6.Mettre à jour le DOM représentant la page à l’aide des nouvelles données.

15 Le code Javascript : popup.js // check if namespace object already exists, if not create it if(typeof(bpui) == 'undefined') { var bpui=new Object(); } // create component namespace object // alone will contain the popup object bpui.alone=new Object(); /* time out variable When a user mouses over a book link in the catalog page, a timer begins counting. If the mouse is still hovering over the link after a timeout period of 1000 ms has elapsed, an XMLHttpRequest request is sent to the server. */ bpui.alone.timeout=""; // object to hold the request bpui.alone.req="";

16 Fonction invoquée lorsque la souris est sur un lien // This is an exposed function to show and position the popup, and start the timer bpui.alone.showPopup=function(eventx, bookId) { // statically setup popup for simple case popupx="pop0"; // take into account window scrolling for accurate popup position var xx=0; var yy=0; if (!eventx) var eventx=window.event; if (eventx.pageX || eventx.pageY){ xx=eventx.pageX; // relatif au coin de la portion visible de la fenêtre yy=eventx.pageY; } else if (eventx.clientX || eventx.clientY) { xx=eventx.clientX + document.body.scrollLeft; // relatif au coin de la fenêtre yy=eventx.clientY + document.body.scrollTop; } document.getElementById(popupx).style.left= (xx + 3) + "px"; document.getElementById(popupx).style.top= (yy - 50) + "px"; //la fonction showPopupInternal sera invoquée à la fin du timeout bpui.alone.timeout=setTimeout("bpui.alone.showPopupInternal('" + popupx + "', '" + bookId + "')", 1000); }

17 Déclenchement de la requête asynchrone // This function is called after initial timeout // that represents the delay bpui.alone.showPopupInternal=function(popupx, bookId) { // set up request (if not IE will not hit server) bpui.alone.req=bpui.alone.initRequest(); // url when using the jsp to serve the ajax request //url="../book_lookup.jsp?bookId=" + escape(bookId); // url when using the servlet to serve the ajax request url="../PopupServlet?bookId=" + escape(bookId); bpui.alone.req.onreadystatechange = bpui.alone.ajaxReturnFunction; bpui.alone.req.open("GET", url, true); bpui.alone.req.send(null); }

18 Fonction de callback lorsque la réponse à la requête est reçue // call back function that is called once the AJAX call returns bpui.alone.ajaxReturnFunction=function() { // statically setup popup for simple case var componentId="pop0"; // check return of the call to make sure it is valid if (bpui.alone.req.readyState == 4) { // ready state is complete (readyState property equals 4) if (bpui.alone.req.status == 200) { // response is OK (status property equals 200) // get results and replace dom elements var resultx=bpui.alone.req.responseXML.getElementsByTagName("response")[0]; // and replace dom elements document.getElementById(componentId + "_title").innerHTML =resultx.getElementsByTagName("title")[0].childNodes[0].nodeValue; document.getElementById(componentId + "_message").innerHTML =resultx.getElementsByTagName("message")[0].childNodes[0].nodeValue;; // show popup with the newly populated information document.getElementById(componentId).style.visibility='visible‘; } else if (bpui.alone.req.status == 204){ alert("204 returned from AJAX call"); } } }

20 Création de l’objet requête // setup request vehicle, need to do each time to make sure call is made to server. bpui.alone.initRequest=function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } }

21 Le fichier css pour décrire l’apparence d’une bulle.bpui_alone_popMid{background: #FFFFFF; border-style: groove; border-width: thin; margin:0px 10px; width: 497px;}.bpui_alone_popTop{background:#696;margin:0px 10px; width: 500px; height:20px;z-index: 1;}.bpui_alone_popTop div.bpui_alone_cornerTL{width:100%;height:20px; background:url("./images/alone_corner_tl.gif") no-repeat top left}.bpui_alone_popTop div.bpui_alone_cornerTR{width:100%;height:20px; background:url("./images/alone_corner_tr.gif") no-repeat top right}.bpui_alone_popBot{background:#696;margin:0px 10px; width: 500px; height:10px;z-index: 1;}.bpui_alone_popBot div.bpui_alone_cornerBL{width:100%;height:10px; background:url("./images/alone_corner_bl.gif") no-repeat bottom left}.bpui_alone_popBot div.bpui_alone_cornerBR{width:100%;height:10px; background:url("./images/alone_corner_br.gif") no-repeat bottom right} div.bpui_alone_popup { position:absolute; left:0px; top:0px; z-index:2; visibility:hidden; }

22 Dans la page html ${book.title}

23 D a n s l e fi c h i e r.j s p title Value

24 Ecrire le servlet public class PopupServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // }

25 Ecrire le servlet public class PopupServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=UTF-8"); PrintWriter out = response.getWriter(); BookstoreMessages messages=new BookstoreMessages(); String bookId=request.getParameter("bookId"); try { out.println(" "); if(bookId != null) { BookDBAO bookDBAO=(BookDBAO)getServletContext().getAttribute("bookDBAO"); Book book=bookDBAO.getBook(bookId); out.println(" "); out.println("

26 Do it yourself : avantages et inconvénients zAvantages yOffers fine-grained control over Ajax processing zInconvénients yRequires a lot of Ajax-related coding yRequires knowledge of multiple languages and technologies yRequires developers to contend with browser incompatibilities yRequires developers to contend with UI issues xBookmark d’une page Ajax : que faut-il garder car l’URL est la même yCan be difficult to debug. yExposes JavaScript technology code -- a potential security risk

27 Design Strategy 2: Use a Client-Side JavaScript Technology Library zUtiliser des librairies qui fournissent des fonctionnalités Ajax yDojo toolkit, Prototype, Script.aculo.us, Rico. zLa libraire dojo.io permet d’abstraire les opération de communication Ajax avec le serveur yCache les détails de bas niveau des opérations XMLHttpRequest. zPrototype yFramework permettant d’abstraire XMLHttpRequest, de manipuler le DOM zScript.aculo.us, Rico construit au-dessus de Prototype yAjax, drag and drop, effets UI, etc.

28 Use a Client-Side JavaScript Technology Library : avantages et inconvénients zAvantages yHides low-level Ajax "plumbing" yReduces the need for JavaScript technology coding yHandles browser incompatibilities in processing Ajax yHandles some common Ajax issues such as bookmarking and support for the Back button. yEstablished user communities for these toolkits can help in answering questions zInconvénients yRequires some knowledge of JavaScript technology yMight need to mix and match JavaScript technology libraries yMight not meet all Ajax needs

29 Design Strategy 3: Use a Client-Server Framework zJavaServer Faces technology frameworks y Java EE 5 SDK, ICEfaces, Ajax4jsf, and Project Dynamic Faces.Java EE 5 SDKICEfacesAjax4jsf z Direct Web Remoting (DWR), yDesign Strategy 5: Go RemoteDesign Strategy 5: Go Remote zGoogle Web Toolkit (GWT) yDesign Strategy 6: Go All Java TechnologyDesign Strategy 6: Go All Java Technology

30 JavaServer Faces (JSF) zdesigned to simplify building functionally rich UIs for web applications. z component model. y a set of APIs for xrepresenting UI components and for managing their state xprogrammatically handling events on components, as well as converting and validating input data yLes composantes s’exécutent sur le serveur et sont « rendues » sur le client yenables application developers to build Ajax into a web application by dragging and dropping visual components. yextensible

31 To use an Ajax-enabled component on a page 1.reference the custom component's tag library, 2.specify the tag for the component, 3.and map a pertinent event to a JavaScript technology function that handles the event.

32 La fonction de lancement de la requête

33 La fonction « callback »

34

35 Use a Client-Server Framework : avantages et inconvénients zAvantages yPage authors do not need to know all of JavaScript technology, CSS, and DOM. yAjax-enabled custom components are reusable. yComponent developers can take advantage of JavaServer Faces technology features yApplication developers can add Ajax to a web application by dragging and dropping visual components zInconvénients yHas many of the same disadvantages as the do-it-yourself approach

36 Design Strategy 4: Do the Wrap Thing zCombining y client-side JavaScript technology libraries y client-server frameworks zjMaki y a framework for wrapping JavaScript technology widgets in JSP tags or JavaServer Faces components.

37 Utilisation de jMAKI zincludes a jMaki widget on a page in the same way as a JSP tag or JavaServer Faces component zDéfinir un widget jMAKI yan HTML template file that specifies the page layout for the widget, ya CSS file that specifies the style parameters for the widget, y a JavaScript technology file that specifies the widget's behavior.

38 Pros and Cons of Using jMaki zPros yHides the JavaScript technology details xjMaki makes widgets available as JSP tags or as JavaServer Faces components yIntegrated into the Project Phobos scripting framework xcreating a framework for building web applications using scripting languages. x allowing to use the Java programming language rather than a scripting language, when appropriate, to perform a task zCons yRequires some knowledge of JavaScript

39 Design Strategy 5: Go Remote zframeworks y Direct Web Remoting (DWR)Direct Web Remoting (DWR) y JSON-RPC.JSON-RPC zenable developers to build Ajax into an application through Remote Procedure Call (RPC)- like calls in JavaScript technology code zServer side ycreate a simple Java class to handle the Ajax requests for the pop-up balloon content. x the class Popup and the method in the class that provides the book details for the pop-up balloon getDetails. z client-side y JavaScript technology function that is triggered in response to the appropriate mouseover event. ywrite the callback function in the client JavaScript technology code

40 The DWR framework zhandle the low-level details y creating, configuring, and performing operations on an XMLHttpRequest object. zgenerates the equivalent of a Remote Method Invocation (RMI) stub on the client for the class. yThat stub is a JavaScript technology class that includes the low-level XMLHttpRequest operations. zmarshals the data exchanged between the generated JavaScript technology class and the server. y converting parameters that the client-side JavaScript technology passes, y converting the values that the server-side Java technology returns. zcreates on the server a servlet ycalled DWRServlet yreceives the request and dispatches it to the Popup class for processing.

41 Go Remote : avantages et inconvénients zAvantages yHides low-level Ajax "plumbing". yAllows Java application developers to make Ajax requests using a familiar syntax yAllows developers to expose existing business logic to an Ajax client with minimum effort yProvides security controls xDWR offers various controls to protect remote classes and methods from unwarranted exposure zInconvénients yRequires knowledge of JavaScript. yOnly works with Java objects

42 Design Strategy 6: Go All Java Technology zGoogle Web Toolkit (GWT).Google Web Toolkit (GWT) zallows developers to build Ajax-enabled applications exclusively in the Java programming language zclient side ya GWT Java-to-JavaScript technology compiler converts the Java programming language code on the client to JavaScript technology code and HTML. zserver-side yJava technologies such as servlets, JSP technology, and JavaServer Faces technology. zBuilding a UI for an Ajax-enabled application using GWT yGWT provides a library of commonly used widgets yJFC/Swing paradigm continues in GWT's event model. zTesting and debugging ya "hosted mode". xruns your client in a Java virtual machine*.* xGWT provides a browser and a simple servlet so that you can do a test run of the application. x set breakpoints that hook back into your Java code. ya "web mode" where you can run the compiled version of the application xthat is, the version that contains the JavaScript technology code and HTML.

43 Go All Java Technology : avantages et inconvénients zAvantages yAllows developers to build Ajax-enabled applications in the Java programming language. xDevelopers do not need to know JavaScript technology, CSS, or DOM. yProvides GWT hosted mode, an environment that enables debugging. yHandles browser incompatibilities in processing Ajax. yDeveloped and supported by Google. zInconvénients yGenerated JavaScript technology code has its drawbacks xyou might sometimes need to examine the generated JavaScript technology code

44

45 iFrame zinline frame zUn élément html qui permet d’imbriquer un autre document html à l’intérieur du document principal.

46 Références zAjax Design Strategies yhttp://java.sun.com/developer/technicalArticles/J2EE/AJAX/DesignStra tegies/http://java.sun.com/developer/technicalArticles/J2EE/AJAX/DesignStra tegies/ zCreating an AJAX-Enabled Application, a Do-It-Yourself Approach yhttp://java.sun.com/developer/technicalArticles/J2EE/hands- on/legacyAJAX/do-it-yourself/index.htmlhttp://java.sun.com/developer/technicalArticles/J2EE/hands- on/legacyAJAX/do-it-yourself/index.html zSurvey of Ajax/JavaScript Libraries.Survey of Ajax/JavaScript Libraries yhttp://chandlerproject.org/bin/view/Projects/AjaxLibrarieshttp://chandlerproject.org/bin/view/Projects/AjaxLibraries zGoogle web toolkit yhttp://code.google.com/webtoolkit/


Download ppt "Ajax. AJAX zAsynchronous Javascript and XML zLa page n’est pas rechargée yRafraîchissement partiel yLa page web est traitée comme un template zAsynchrone."

Similar presentations


Ads by Google