Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Introduction to AJAX and DWR
1. AJAX and DWR a little introduce to By SweNz swenz@live.it
2. 1 Introduce to AJAX 2 Introduce to DWR focus on Reverse AJAX 3 Contents
3. What is AJAX ? AJAX is .. AJAX : Asynchronous JavaScript and XML Asynchronous JavaScript AJAX was introduced in 18 Feb 2005 by Jesse James Garrett. AJAX And XML Ajax is a technique creating better, faster, and more interactive web applications.
4. Defining AJAX dynamic display and interaction using the Document Object Model (DOM) Standards - based presentation using XHTML and CSS asynchronous data retrieval using XMLHttpRequest data interchange and manipulation using XML and XSLT JavaScript binding everything together
5. uninterrupted user operation while data is being fetched display and interact with the information presented dynamically platform or language, and no plug-in required independent AJAX Advantage
15. Processing the Server Response XMLHttpRequest object provides two properties that provide access to the server response. responseText- provides the response as a string. responseXML - provides the response as an XML object
18. 18 Date Validation Create XMLHttpRequest object var xmlHttp; function createXMLHttpRequest(){ if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } }
19. 19 Date Validation Create validate() method function validate() { createXMLHttpRequest(); var date = document.getElementById("birthDate"); var url = "${pageContext.request.contextPath}/ ValidationServlet?birthDate=" + escape(date.value); xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = callback; xmlHttp.send(null); }
20. 20 Date Validation Create callback() method function callback(){ if (xmlHttp.readyState== 4) { if (xmlHttp.status == 200) { varmes= xmlHttp.responseXML. getElementsByTagName("message")[0].firstChild.data; varval= xmlHttp.responseXML. getElementsByTagName("passed")[0].firstChild.data; setMessage(mes, val); } } }
21. Date Validation Set output ‘s format for display in jsp page function setMessage(message, isValid) { varmessageArea= document.getElementById("dateMessage"); varfontColor= "red"; if (isValid== "true") { fontColor= "green"; } messageArea.innerHTML= "<font color=" + fontColor+ ">" + message + " </font>"; }
22. Date Validation Create servlet to validate date from jsp page PrintWriter out = response.getWriter(); try { boolean passed = validateDate(request.getParameter("birthDate")); response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); String message = "You have entered an invalid date."; if (passed) { message = "You have entered a valid date."; } out.println("<response>"); out.println("<passed>" + Boolean.toString(passed) + "</passed>"); out.println("<message>" + message + "</message>"); out.println("</response>"); out.close(); } finally { out.close(); }
24. DWR ( Direct web Remoting) DWR is a RPC library which makes it easy to call Java functions from JavaScript and to call JavaScript functions from Java (a.k.a Reverse Ajax).
25. DWR consist .. DWR consists of two main parts A Java Servlet running on the server that processes requests and sends responses back to the browser. JavaScript running in the browser that sends requests and can dynamically update the webpage
28. Prepare to use DWR 1> We have to download and install DWR.jar to WEB-INF/libalso requires commons-logging. 2> edit the config files in WEB-INF 2.1> edit web.xml 2.2> create dwr.xml
29. web.xml The <servlet> section needs to go with the other <servlet> sections, and likewise with the <servlet-mapping> section. <servlet> <servlet-name>dwr-invoker</servlet-name> <display-name>DWR Servlet</display-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
30. dwr.xml The <servlet> section needs to go with the other <servlet> sections, and likewise with the <servlet-mapping> section. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN“ "http://getahead.org/dwr/dwr30.dtd"> <dwr> <allow> <create creator="new" javascript="EmployeeService"> <param name="class" value="com.dwr.service.EmployeeService"/> </create> <convert converter="bean" match="com.dwr.bean.EmployeeBean" /> </allow> </dwr>
31. if everything ok .. start your web server such as Tomcat then open URL : [YOUR-WEBAPP]/dwr/ e.g. : http://localhost:8084/DwrProject/dwr/ You will got web page like this :
32. get JavaScript code DWR will generate JavaScript file for knew JAVA class , you can see by click on class name it’ll redirect you to page like this : You must put code in red circle to webpage that want to call java method.
33. ServiceEmployee.java (1) package com.dwr.service; import com.dwr.bean.EmployeeBean; import java.sql.*; public class EmployeeService{ public EmployeeService() {} public EmployeeBeangetChange(String id){ EmployeeBean bean = new EmployeeBean(); bean.setId(id); bean.setName("Not found"); bean.setAddress("Not found"); if(id!=null){ try{ String sql = "select * from employee where employeeid like '"+id+"'";
39. RESTRICTION DWR has a few restrictions Avoid reserved JavaScript words Methods named after reserved words are automatically excluded. Most JavaScript reserved words are also Java reserved words, so you won't be having a method called "try()" anyway. However the most common gotcha is "delete()", which has special meaning from JavaScript but not Java Avoid overloaded methods Overloaded methods can be involved in a bit of a lottery as to which gets called
40. What is Reverse AJAX “Reverse Ajax is the biggest new feature in DWR 2.0. It gives you the ability to asynchronously send data from a web-server to a browser” DWR supports 3 methods of pushing the data from to the browser: Piggyback, Polling and Comet.
41. Polling This is where the browser makes a request of the server at regular and frequent intervals, say every 3 seconds, to see if there has been an update to the page. It's like 5 year old in the back of the car shouting 'are we there yet?' every few seconds.
42. Comet AKA long lived http, server push allows the server to start answering the browser's request for information very slowly, and to continue answering on a schedule dictated by the server.
43. Piggyback ( Passive Mode) the server, having an update to send, waits for the next time the browser makes a connection and then sends it's update along with the response that the browser was expecting.
44. Active and Passive Reverse Ajax DWR can be configured to use Comet/Polling for times when extra load is acceptable, but faster response times are needed. This mode is called active Reverse Ajax. By default DWR starts with active Reverse Ajax turned off, allowing only the piggyback transfer mechanism. to request active Reverse Ajax in a web page. This begins a Comet/polling cycle. Just call the following as part of the page load event: dwr.engine.setActiveReverseAjax(true);
45. Configuring Active Reverse Ajax Active Reverse Ajax can be broken down into 3 modes: Full Streaming Mode Early Closing Mode Polling Mode
46. Full Streaming Mode This is the default mode when Active Reverse Ajax is turned on (before 2.0.4 after that using Early Closing). It has the fastest response characteristics because it closes connections only once every 60 seconds or so to check that the browser is still active
47. Full Streaming Mode (2) WEB-INF/web.xml <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>maxWaitAfterWrite</param-name> <param-value>-1</param-value> </init-param> </servlet> You also need to request Active Reverse Ajax from a web page: dwr.engine.setActiveReverseAjax(true);
48. Early Closing Mode DWR holds connection open as it did in Full Streaming Mode, however it only holds the connection open for 60 seconds if there is no output to the browser. Once output occurs, DWR pauses for some configurable time before closing the connection, forcing proxies to pass any messages on.
49. Early Closing Mode <init-param> <param-name>maxWaitAfterWrite</param-name> <param-value>500</param-value> </init-param>
50. Polling Mode If it is deemed unwise to hold connections open at all then DWR can use polling mode.
51. Polling Mode (2) you should specify the PollingServerLoadMonitor as follows: <init-param> <param-name>org.directwebremoting.extend.ServerLoadMonitor</param-name> <param-value>org.directwebremoting.impl.PollingServerLoadMonitor</param-value> </init-param> <init-param> <param-name>disconnectedTime</param-name> <param-value>60000</param-value> </init-param>