SlideShare uma empresa Scribd logo
1 de 54
AJAX and DWR a little introduce to By SweNz swenz@live.it
1 Introduce to AJAX 2 Introduce to DWR focus on Reverse AJAX 3 Contents
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.
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
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
Still browser incompatibility is hard to maintain and debug JavaScript make AJAX Disadvantage
Compare classic and AJAX web application model
XMLHttpRequest
Creating XMLHttpRequest native JavaScriptObject (Other Browsers) varxhr; function createXMLHttpRequest() { 	if (window.XMLHttpRequest) { xhr= new XMLHttpRequest(); 	} 	else if (window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); 	} else {    alert("XMLHttpRequest not supported");   	    return null; } } ActiveX Object (IE)
Use XMLHttpRequest function run() {  varreq = createXMLHttpRequest(); //สร้าง Object  req.open('GET', ‘abc.isp', true); //กำหนด สถานะการทำงานของ AJAX  req.onreadystatechange = function() { //เหตุการณ์เมื่อมีการตอบกลับ    if (req.readyState == 4) {      if (req.status == 200) { //ได้รับการตอบกลับเรียบร้อย        var data = req.responseText; //ข้อความที่ได้มาจากการทำงานของ abc.jsp        document.getElementById("content").innerHTML = 	"ข้อความที่ตอบกลับจาก server คือ "+data; //แสดงผล      }    }  };  req.setRequestHeader("Content-Type",  	"application/x-www-form-urlencoded"); //Header ที่ส่งไป  req.send(null); //ทำการส่ง};
About readyState property
Standard XMLHttpRequest Operation
Standard XMLHttpRequest Properties
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
implement basic AJAX Entering an invalid date Entering an valid date
17 Date Validation Create validation.jsp page <body>     <h1>Ajax Validation Example</h1>         Birth date:  	<input type="text" size="10" id="birthDate" 			onchange="validate();"/>     <div id="dateMessage"></div> </body>
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 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 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);                 }             } }
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>"; }
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();         }
Date Validation private booleanvalidateDate(String date) { booleanisValid = true;         if(date != null) { SimpleDateFormat formatter= new            SimpleDateFormat("MM/dd/yyyy");             try { formatter.parse(date);             } catch (ParseExceptionpe) { System.out.println(pe.toString()); isValid = false;             }         } else { isValid = false;         }         return isValid; }
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).
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
How it work ? (1) AJAX Style
How it work ? (2) Reverse  AJAX
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
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>
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>
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 :
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.
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+"'";
ServiceEmployee.java (2) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();                Connection con = DriverManager.getConnection("jdbc:odbc:dwrdb");              	 Statement stm = con.createStatement(); ResultSetrs = stm.executeQuery(sql);                 if(rs.next()) { bean.setName(rs.getString("employeename")); bean.setAddress(rs.getString("address")); 				}         }catch(Exception ex){ ex.printStackTrace(); 	} 	}         return bean;     } }
EmployeeBean.java package com.dwr.bean; public class EmployeeBean{   private String id;   private String name;   private String address;   public EmployeeBean() {   }     public String getId() {     return id;   }   public String getName() {     return name;   }   public String getAddress() {     return address;   } public void setId(String id) {     this.id = id;   }   public void setName(String name) {     this.name = name;   }   public void setAddress(String address) { this.address = address;   }   }
Test DWR (1) Create employee.jsp like this : <script type='text/javascript' src='dwr/interface/EmployeeService.js'></script>  <script type='text/javascript' src='dwr/engine.js'></script>  <script type='text/javascript' src='dwr/util.js'></script> <script language="JavaScript"> function getChange() { EmployeeService.getChange(employeeid.value,loadChange); } function loadChange(data) { EmpField.innerHTML = "ID : "+data.id+"<br>Name : "+data.name+"<br>Address : "+data.address; } </script>
Test DWR (2) <BODY> <h1>Employee Service</h1> <table> 	<tr> 	<td>Employee ID</td> 	<td><input type="text" id="employeeid"   onblur="getChange()" ></input></td>     </tr> </table> <div id="EmpField"></div> <div id="LogLayer"></div> </BODY>
Result :
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
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.
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.
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.
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.
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);
Configuring Active Reverse Ajax 	Active Reverse Ajax  	can be broken down into 3 modes: Full Streaming Mode Early Closing Mode Polling Mode
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
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);
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.
Early Closing Mode <init-param>  	<param-name>maxWaitAfterWrite</param-name>  	<param-value>500</param-value>  </init-param>
Polling Mode 	If it is deemed unwise to hold connections open at all then DWR can use polling mode.
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>
Q & A  > <!!
Reference http://www.adaptivepath.com/ideas/essays/archives/000385.php http://java.sun.com/developer/technicalArticles/J2EE/AJAX/ https://developer.mozilla.org/en/AJAX http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-dwr.html http://directwebremoting.org/dwr/reverse-ajax/index.html http://directwebremoting.org/dwr/index.html http://ajaxian.com/archives/reverse-ajax-with-dwr http://en.wikipedia.org/wiki/Reverse_Ajax http://en.wikipedia.org/wiki/Ajax_(programming) http://www.adaptivepath.com/ideas/essays/archives/000385.php http://msdn.microsoft.com/en-us/library/ms534361(VS.85).aspx
Thank You! SweNzFiXed

Mais conteúdo relacionado

Mais procurados

JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
giurca
 

Mais procurados (20)

Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactions
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
AngularJs
AngularJsAngularJs
AngularJs
 
Ajax
AjaxAjax
Ajax
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
FYBSC IT Web Programming Unit III Core Javascript
FYBSC IT Web Programming Unit III  Core JavascriptFYBSC IT Web Programming Unit III  Core Javascript
FYBSC IT Web Programming Unit III Core Javascript
 

Destaque (10)

Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Hibernate
HibernateHibernate
Hibernate
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Json
JsonJson
Json
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 

Semelhante a Introduction to AJAX and DWR

Liferay Training Struts Portlet
Liferay Training Struts PortletLiferay Training Struts Portlet
Liferay Training Struts Portlet
Saikrishna Basetti
 
Introduction to javaScript
Introduction to javaScriptIntroduction to javaScript
Introduction to javaScript
Neil Ghosh
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 

Semelhante a Introduction to AJAX and DWR (20)

Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Interoperable Web Services with JAX-WS
Interoperable Web Services with JAX-WSInteroperable Web Services with JAX-WS
Interoperable Web Services with JAX-WS
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
Liferay Training Struts Portlet
Liferay Training Struts PortletLiferay Training Struts Portlet
Liferay Training Struts Portlet
 
my accadanic project ppt
my accadanic project pptmy accadanic project ppt
my accadanic project ppt
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Introduction to javaScript
Introduction to javaScriptIntroduction to javaScript
Introduction to javaScript
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Yahoo Query Language: Select * from Internet
Yahoo Query Language: Select * from InternetYahoo Query Language: Select * from Internet
Yahoo Query Language: Select * from Internet
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
AJAX Workshop Notes
AJAX Workshop NotesAJAX Workshop Notes
AJAX Workshop Notes
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 

Último

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
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
  • 6. Still browser incompatibility is hard to maintain and debug JavaScript make AJAX Disadvantage
  • 7. Compare classic and AJAX web application model
  • 8.
  • 10. Creating XMLHttpRequest native JavaScriptObject (Other Browsers) varxhr; function createXMLHttpRequest() { if (window.XMLHttpRequest) { xhr= new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("XMLHttpRequest not supported");    return null; } } ActiveX Object (IE)
  • 11. Use XMLHttpRequest function run() {  varreq = createXMLHttpRequest(); //สร้าง Object  req.open('GET', ‘abc.isp', true); //กำหนด สถานะการทำงานของ AJAX  req.onreadystatechange = function() { //เหตุการณ์เมื่อมีการตอบกลับ    if (req.readyState == 4) {      if (req.status == 200) { //ได้รับการตอบกลับเรียบร้อย        var data = req.responseText; //ข้อความที่ได้มาจากการทำงานของ abc.jsp        document.getElementById("content").innerHTML = "ข้อความที่ตอบกลับจาก server คือ "+data; //แสดงผล      }    }  };  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Header ที่ส่งไป  req.send(null); //ทำการส่ง};
  • 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
  • 16. implement basic AJAX Entering an invalid date Entering an valid date
  • 17. 17 Date Validation Create validation.jsp page <body> <h1>Ajax Validation Example</h1> Birth date: <input type="text" size="10" id="birthDate" onchange="validate();"/> <div id="dateMessage"></div> </body>
  • 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(); }
  • 23. Date Validation private booleanvalidateDate(String date) { booleanisValid = true; if(date != null) { SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy"); try { formatter.parse(date); } catch (ParseExceptionpe) { System.out.println(pe.toString()); isValid = false; } } else { isValid = false; } return isValid; }
  • 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
  • 26. How it work ? (1) AJAX Style
  • 27. How it work ? (2) Reverse AJAX
  • 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+"'";
  • 34. ServiceEmployee.java (2) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); Connection con = DriverManager.getConnection("jdbc:odbc:dwrdb"); Statement stm = con.createStatement(); ResultSetrs = stm.executeQuery(sql); if(rs.next()) { bean.setName(rs.getString("employeename")); bean.setAddress(rs.getString("address")); } }catch(Exception ex){ ex.printStackTrace(); } } return bean; } }
  • 35. EmployeeBean.java package com.dwr.bean; public class EmployeeBean{ private String id; private String name; private String address; public EmployeeBean() { } public String getId() { return id; } public String getName() { return name; } public String getAddress() { return address; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } }
  • 36. Test DWR (1) Create employee.jsp like this : <script type='text/javascript' src='dwr/interface/EmployeeService.js'></script> <script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script language="JavaScript"> function getChange() { EmployeeService.getChange(employeeid.value,loadChange); } function loadChange(data) { EmpField.innerHTML = "ID : "+data.id+"<br>Name : "+data.name+"<br>Address : "+data.address; } </script>
  • 37. Test DWR (2) <BODY> <h1>Employee Service</h1> <table> <tr> <td>Employee ID</td> <td><input type="text" id="employeeid" onblur="getChange()" ></input></td> </tr> </table> <div id="EmpField"></div> <div id="LogLayer"></div> </BODY>
  • 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>
  • 52. Q & A > <!!
  • 53. Reference http://www.adaptivepath.com/ideas/essays/archives/000385.php http://java.sun.com/developer/technicalArticles/J2EE/AJAX/ https://developer.mozilla.org/en/AJAX http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-dwr.html http://directwebremoting.org/dwr/reverse-ajax/index.html http://directwebremoting.org/dwr/index.html http://ajaxian.com/archives/reverse-ajax-with-dwr http://en.wikipedia.org/wiki/Reverse_Ajax http://en.wikipedia.org/wiki/Ajax_(programming) http://www.adaptivepath.com/ideas/essays/archives/000385.php http://msdn.microsoft.com/en-us/library/ms534361(VS.85).aspx

Notas do Editor

  1. by the way , I’m Thai not Italian , please e-mail me in english . Thanks for interest