Скачать презентацию Ajax AJAX z Asynchronous Javascript and XML Скачать презентацию Ajax AJAX z Asynchronous Javascript and XML

4b54cb5b7a2ee79a6cfa86daec13dd47.ppt

  • Количество слайдов: 46

Ajax Ajax

AJAX z Asynchronous Javascript and XML z La page n’est pas rechargée y Rafraîchissement AJAX z Asynchronous Javascript and XML z La page n’est pas rechargée y Rafraîchissement partiel y La page web est traitée comme un template z Asynchrone y Le client peut continuer à interagir en attente de la réponse z Utilisation y y Validation par le serveur des données d’un formulaire en temps réel Auto-complétion Préchargement à la demande. Contrôles et effets sophistiquées dans les interfaces usager sans rechargement des pages x progress bar, calendriers, arbres… y Rafraîchissement des données et mode « push » par le serveur y Soumission partielle sans rechargement de la page: listes de formulaires dépendants. y Mashups x obtenir et intégrer des données provenant de plusieurs sources. y Page == application qui s’approche d’une application desktop.

Technologies utilisées par Ajax z Cascading Style Sheets (CSS) y Un langage de balises Technologies utilisées par Ajax z Cascading Style Sheets (CSS) y Un langage de balises pour définir le style de présentation d’une page, e. g. polices, couleurs. . z Java. Script y Élément clé : l’objet XMLHttp. Request utilisé pour échanger des données entre le client web et le serveur web z Document Object Model (DOM) y Fournit une vue logique de la page web sous forme d’arbre z XML y Format d’échange de données entre le serveur web et le client x D’autres formats peuvent aussi être utilisés • Par exemple, HTML, Java. Script Object Notation (JSON), ou texte simple.

Fonctionnement Fonctionnement

Ajax et Javascript Ajax et Javascript

z Les différents états d’une requête z Les différents états d’une requête

Les propriétés d’une requête XMLHttp. Request Les propriétés d’une requête XMLHttp. Request

Les méthodes d’une requête XMLHttp. Request Les méthodes d’une requête XMLHttp. Request

Construction et envoi d’une requête Post Construction et envoi d’une requête Post

Ajax et Java Ajax et Java

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

Design Strategy 1: Do It Yourself z Client y Écrire soi-même le code en Design Strategy 1: Do It Yourself z Client y Écrire soi-même le code en x Java. Script, x CSS, x DOM, x Présentation de la page. z Serveur y Coder explicitement la gestion de l’appel XMLHttp. Request y Rendre une réponse appropriée x Par exemple en XML

Exemple z Implémenter une bulle pop-up Exemple z Implémenter une bulle pop-up

Etapes à réaliser 1. Associer l’événement à une fonction Java. Script. 2. Créer et Etapes à réaliser 1. Associer l’événement à une fonction Java. Script. 2. Créer et configurer un objet XMLHttp. Request. 3. Faire une requête au serveur à travers l’objet XMLHttp. Request. 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 Java. Script de callback(). 6. Mettre à jour le DOM représentant la page à l’aide des nouvelles données.

Le code Javascript : popup. js // check if namespace object already exists, if 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 XMLHttp. Request request is sent to the server. */ bpui. alone. timeout=""; // object to hold the request bpui. alone. req="";

Fonction invoquée lorsque la souris est sur un lien // This is an exposed 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. show. Popup=function(eventx, book. Id) { // statically setup popup for simple case popupx="pop 0"; // take into account window scrolling for accurate popup position var xx=0; var yy=0; if (!eventx) var eventx=window. event; if (eventx. page. X || eventx. page. Y){ xx=eventx. page. X; // relatif au coin de la portion visible de la fenêtre yy=eventx. page. Y; } else if (eventx. client. X || eventx. client. Y) { xx=eventx. client. X + document. body. scroll. Left ; // relatif au coin de la fenêtre yy=eventx. client. Y + document. body. scroll. Top; } document. get. Element. By. Id(popupx). style. left = (xx + 3) + "px"; document. get. Element. By. Id(popupx). style. top = (yy - 50) + "px"; } //la fonction show. Popup. Internal sera invoquée à la fin du timeout bpui. alone. timeout=set. Timeout("bpui. alone. show. Popup. Internal ('" + popupx + "', '" + book. Id + "')", 1000);

Déclenchement de la requête asynchrone // This function is called after initial timeout // Déclenchement de la requête asynchrone // This function is called after initial timeout // that represents the delay bpui. alone. show. Popup. Internal=function(popupx, book. Id) { // set up request (if not IE will not hit server) bpui. alone. req=bpui. alone. init. Request(); // url when using the jsp to serve the ajax request //url=". . /book_lookup. jsp? book. Id=" + escape(book. Id); // url when using the servlet to serve the ajax request url=". . /Popup. Servlet? book. Id=" + escape(book. Id); bpui. alone. req. onreadystatechange = bpui. alone. ajax. Return. Function; bpui. alone. req. open("GET", url, true); bpui. alone. req. send(null); }

Fonction de callback lorsque la réponse à la requête est reçue // call back 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. ajax. Return. Function=function() { // statically setup popup for simple case var component. Id="pop 0"; // check return of the call to make sure it is valid if (bpui. alone. req. ready. State == 4) { // ready state is complete (ready. State 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. response. XML. get. Elements. By. Tag. Name("response")[0]; // and replace dom elements document. get. Element. By. Id(component. Id + "_title"). inner. HTML =resultx. get. Elements. By. Tag. Name("title")[0]. child. Nodes[0]. node. Value; document. get. Element. By. Id(component. Id + "_message"). inner. HTML =resultx. get. Elements. By. Tag. Name("message")[0]. child. Nodes[0]. node. Value; ; // show popup with the newly populated information document. get. Element. By. Id(component. Id). style. visibility='visible‘; } else if (bpui. alone. req. status == 204){ alert("204 returned from AJAX call"); } }

La fonction bpui. alone. hide. Popup() est invoquée sur l’événement « mouseout » pour La fonction bpui. alone. hide. Popup() est invoquée sur l’événement « mouseout » pour cacher le ballon et réinitialiser le timeout // This is an exposed function to hide the popup and/or cancel to showing of the popup bpui. alone. hide. Popup=function() { // statically setup popup for simple case popupx="pop 0"; document. get. Element. By. Id(popupx). style. visibility='hidden'; bpui. alone. clear. Timeout(); } // This is an exposed function to clear the timer of the popup // in the mouseout event handler // if the showing of the popup is required bpui. alone. clear. Timeout=function() { clear. Timeout(bpui. alone. timeout); }

Création de l’objet requête // setup request vehicle, need to do each time to 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. init. Request=function() { if (window. XMLHttp. Request) { return new XMLHttp. Request(); } else if (window. Active. XObject) { return new Active. XObject("Microsoft. XMLHTTP"); } }

Le fichier css pour décrire l’apparence d’une bulle. bpui_alone_pop. Mid{background: #FFFFFF; border-style: groove; border-width: Le fichier css pour décrire l’apparence d’une bulle. bpui_alone_pop. Mid{background: #FFFFFF; border-style: groove; border-width: thin; margin: 0 px 10 px; width: 497 px; }. bpui_alone_pop. Top{background: #696; margin: 0 px 10 px; width: 500 px; height: 20 px; z-index: 1; }. bpui_alone_pop. Top div. bpui_alone_corner. TL{width: 100%; height: 20 px; background: url(". /images/alone_corner_tl. gif") no-repeat top left}. bpui_alone_pop. Top div. bpui_alone_corner. TR{width: 100%; height: 20 px; background: url(". /images/alone_corner_tr. gif") no-repeat top right}. bpui_alone_pop. Bot{background: #696; margin: 0 px 10 px; width: 500 px; height: 10 px; z-index: 1; }. bpui_alone_pop. Bot div. bpui_alone_corner. BL{width: 100%; height: 10 px; background: url(". /images/alone_corner_bl. gif") no-repeat bottom left}. bpui_alone_pop. Bot div. bpui_alone_corner. BR{width: 100%; height: 10 px; background: url(". /images/alone_corner_br. gif") no-repeat bottom right} div. bpui_alone_popup { position: absolute; left: 0 px; top: 0 px; z-index: 2; visibility: hidden; }

Dans la page html <a href= Dans la page html ${book. title} 

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

title
Value

Ecrire le servlet public class Popup. Servlet extends Http. Servlet { protected void do. Ecrire le servlet public class Popup. Servlet extends Http. Servlet { protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { process. Request(request, response); } protected void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { process. Request(request, response); } /** Returns a short description of the servlet. */ public String get. Servlet. Info() { return "Short description"; } // }

Ecrire le servlet public class Popup. Servlet extends Http. Servlet { protected void process. Ecrire le servlet public class Popup. Servlet extends Http. Servlet { protected void process. Request(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/xml; charset=UTF-8"); Print. Writer out = response. get. Writer(); Bookstore. Messages messages=new Bookstore. Messages(); String book. Id=request. get. Parameter("book. Id"); try { out. println(""); if(book. Id != null) { Book. DBAO book. DBAO=(Book. DBAO)get. Servlet. Context (). get. Attribute("book. DBAO"); Book book=book. DBAO. get. Book(book. Id); out. println("<![CDATA[Book Detail]]>"); out. println("" + book. get. Title() + "
"); // etc. } } catch(Exception ee) { ee. print. Stack. Trace(); } finally { out. println("
"); out. flush(); out. close(); } }

Do it yourself : avantages et inconvénients z Avantages y Offers fine-grained control over Do it yourself : avantages et inconvénients z Avantages y Offers fine-grained control over Ajax processing z Inconvénients y Requires a lot of Ajax-related coding y Requires knowledge of multiple languages and technologies y Requires developers to contend with browser incompatibilities y Requires developers to contend with UI issues x Bookmark d’une page Ajax : que faut-il garder car l’URL est la même y Can be difficult to debug. y Exposes Java. Script technology code -- a potential security risk

Design Strategy 2: Use a Client-Side Java. Script Technology Library z Utiliser des librairies Design Strategy 2: Use a Client-Side Java. Script Technology Library z Utiliser des librairies qui fournissent des fonctionnalités Ajax y Dojo toolkit, Prototype, Script. aculo. us, Rico. z La libraire dojo. io permet d’abstraire les opération de communication Ajax avec le serveur y Cache les détails de bas niveau des opérations XMLHttp. Request. z Prototype y Framework permettant d’abstraire XMLHttp. Request, de manipuler le DOM z Script. aculo. us, Rico construit au-dessus de Prototype y Ajax, drag and drop, effets UI, etc.

Use a Client-Side Java. Script Technology Library : avantages et inconvénients z Avantages y Use a Client-Side Java. Script Technology Library : avantages et inconvénients z Avantages y Hides low-level Ajax "plumbing" y Reduces the need for Java. Script technology coding y Handles browser incompatibilities in processing Ajax y Handles some common Ajax issues such as bookmarking and support for the Back button. y Established user communities for these toolkits can help in answering questions z Inconvénients y Requires some knowledge of Java. Script technology y Might need to mix and match Java. Script technology libraries y Might not meet all Ajax needs

Design Strategy 3: Use a Client-Server Framework z Java. Server Faces technology frameworks y Design Strategy 3: Use a Client-Server Framework z Java. Server Faces technology frameworks y Java EE 5 SDK, ICEfaces, Ajax 4 jsf, and Project Dynamic Faces. z Direct Web Remoting (DWR), y. Design Strategy 5: Go Remote z Google Web Toolkit (GWT) y. Design Strategy 6: Go All Java Technology

Java. Server Faces (JSF) z designed to simplify building functionally rich UIs for web Java. Server Faces (JSF) z designed to simplify building functionally rich UIs for web applications. z component model. y a set of APIs for x representing UI components and for managing their state x programmatically handling events on components, as well as converting and validating input data y Les composantes s’exécutent sur le serveur et sont « rendues » sur le client y enables application developers to build Ajax into a web application by dragging and dropping visual components. y extensible

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

La fonction de lancement de la requête La fonction de lancement de la requête

La fonction « callback » La fonction « callback »

Use a Client-Server Framework : avantages et inconvénients z Avantages y Page authors do Use a Client-Server Framework : avantages et inconvénients z Avantages y Page authors do not need to know all of Java. Script technology, CSS, and DOM. y Ajax-enabled custom components are reusable. y Component developers can take advantage of Java. Server Faces technology features y Application developers can add Ajax to a web application by dragging and dropping visual components z Inconvénients y Has many of the same disadvantages as the do-it-yourself approach

Design Strategy 4: Do the Wrap Thing z Combining y client-side Java. Script technology Design Strategy 4: Do the Wrap Thing z Combining y client-side Java. Script technology libraries y client-server frameworks z j. Maki y a framework for wrapping Java. Script technology widgets in JSP tags or Java. Server Faces components.

Utilisation de j. MAKI z includes a j. Maki widget on a page in Utilisation de j. MAKI z includes a j. Maki widget on a page in the same way as a JSP tag or Java. Server Faces component z Définir un widget j. MAKI y an HTML template file that specifies the page layout for the widget, y a CSS file that specifies the style parameters for the widget, y a Java. Script technology file that specifies the widget's behavior.

Pros and Cons of Using j. Maki z Pros y. Hides the Java. Script Pros and Cons of Using j. Maki z Pros y. Hides the Java. Script technology details xj. Maki makes widgets available as JSP tags or as Java. Server Faces components y. Integrated 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 z Cons y. Requires some knowledge of Java. Script

Design Strategy 5: Go Remote z frameworks y Direct Web Remoting (DWR) y JSON-RPC. Design Strategy 5: Go Remote z frameworks y Direct Web Remoting (DWR) y JSON-RPC. z enable developers to build Ajax into an application through Remote Procedure Call (RPC)like calls in Java. Script technology code z Server side y create 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 get. Details. z client-side y Java. Script technology function that is triggered in response to the appropriate mouseover event. y write the callback function in the client Java. Script technology code

The DWR framework z handle the low-level details y creating, configuring, and performing operations The DWR framework z handle the low-level details y creating, configuring, and performing operations on an XMLHttp. Request object. z generates the equivalent of a Remote Method Invocation (RMI) stub on the client for the class. y That stub is a Java. Script technology class that includes the low-level XMLHttp. Request operations. z marshals the data exchanged between the generated Java. Script technology class and the server. y converting parameters that the client-side Java. Script technology passes, y converting the values that the server-side Java technology returns. z creates on the server a servlet y called DWRServlet y receives the request and dispatches it to the Popup class for processing.

Go Remote : avantages et inconvénients z Avantages y Hides low-level Ajax Go Remote : avantages et inconvénients z Avantages y Hides low-level Ajax "plumbing". y Allows Java application developers to make Ajax requests using a familiar syntax y Allows developers to expose existing business logic to an Ajax client with minimum effort y Provides security controls x DWR offers various controls to protect remote classes and methods from unwarranted exposure z Inconvénients y Requires knowledge of Java. Script. y Only works with Java objects

Design Strategy 6: Go All Java Technology z Google Web Toolkit (GWT). z allows Design Strategy 6: Go All Java Technology z Google Web Toolkit (GWT). z allows developers to build Ajax-enabled applications exclusively in the Java programming language z client side y a GWT Java-to-Java. Script technology compiler converts the Java programming language code on the client to Java. Script technology code and HTML. z server-side y Java technologies such as servlets, JSP technology, and Java. Server Faces technology. z Building a UI for an Ajax-enabled application using GWT y GWT provides a library of commonly used widgets y JFC/Swing paradigm continues in GWT's event model. z Testing and debugging y a "hosted mode". x runs your client in a Java virtual machine*. x GWT 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. y a "web mode" where you can run the compiled version of the application x that is, the version that contains the Java. Script technology code and HTML.

Go All Java Technology : avantages et inconvénients z Avantages y Allows developers to Go All Java Technology : avantages et inconvénients z Avantages y Allows developers to build Ajax-enabled applications in the Java programming language. x Developers do not need to know Java. Script technology, CSS, or DOM. y Provides GWT hosted mode, an environment that enables debugging. y Handles browser incompatibilities in processing Ajax. y Developed and supported by Google. z Inconvénients y Generated Java. Script technology code has its drawbacks x you might sometimes need to examine the generated Java. Script technology code

i. Frame z inline frame z Un élément html qui permet d’imbriquer un autre i. Frame z inline frame z Un élément html qui permet d’imbriquer un autre document html à l’intérieur du document principal.

Références z Ajax Design Strategies y http: //java. sun. com/developer/technical. Articles/J 2 EE/AJAX/Design. Stra Références z Ajax Design Strategies y http: //java. sun. com/developer/technical. Articles/J 2 EE/AJAX/Design. Stra tegies/ z Creating an AJAX-Enabled Application, a Do-It-Yourself Approach y http: //java. sun. com/developer/technical. Articles/J 2 EE/handson/legacy. AJAX/do-it-yourself/index. html z Survey of Ajax/Java. Script Libraries. y http: //chandlerproject. org/bin/view/Projects/Ajax. Libraries z Google web toolkit y http: //code. google. com/webtoolkit/