introduction to ajax and dwr

Post on 22-Dec-2014

4.353 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

little introduction to AJAX and DWR

TRANSCRIPT

L/O/G/Owww.themegallery.com

AJAX and DWRa little introduce to

By SweNz

swenz@live.it

Introduce to AJAX

Introduce to DWR

focus on Reverse AJAX

1

2

3

Contents

What is AJAX ?AJAX is ..

AJAX

AJAX : Asynchronous JavaScript and XML

AJAX was introduced in 18 Feb 2005 by Jesse James Garrett.

Ajax is a technique creating better, faster, and more interactive web applications.

Defining AJAX

data interchange and manipulation using XML and XSLT

Standards - based

presentation using XHTML

and CSS

dynamic display and interaction using the Document Object Model (DOM)

asynchronous data

retrieval using

XMLHttpRequest

JavaScript binding everything together

user operation while data is being fetched

uninterrupted

dynamically

independent

display and interact with the information presented

platform or language, and no plug-in required

AJAX Advantage

browser incompatibilityStill

JavaScript

make

is hard to maintain and debug

AJAX Disadvantage

Compare classic and AJAX web application model

XMLHttpRequest

Creating XMLHttpRequest

var xhr;

function createXMLHttpRequest() {if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest();}else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP");}else { alert("XMLHttpRequest not supported");

    return null;}

}

native JavaScript Object (Other Browsers)

ActiveX Object (IE)

Use XMLHttpRequestfunction run() {

  var req = 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 propertyValue Status Description

0 Uninitialized The object has been created, but not initialized (the open method has not been called).

1 Loading The object has been created, but the send method has not been called.

2 Loaded The send method has been called. responseText is not available. responseBody is not available.

3 Interactive Some data has been received. responseText is not available. responseBody is not available.

4 Complete All the data has been received. responseText is available. responseBody is available.

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) { var mes = xmlHttp.responseXML. getElementsByTagName("message")[0].firstChild.data; var val = 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) { var messageArea = document.getElementById("dateMessage"); var fontColor = "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 Validationprivate boolean validateDate(String date) { boolean isValid = true; if(date != null) { SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy"); try { formatter.parse(date); } catch (ParseException pe) { 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/lib also requires commons-logging.

2> edit the config files in WEB-INF

2.1> edit web.xml

2.2> create dwr.xml

web.xml

<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>

The <servlet> section needs to go with the other <servlet> sections, and likewise with the <servlet-mapping> section.

dwr.xml

<?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>

The <servlet> section needs to go with the other <servlet> sections, and likewise with the <servlet-mapping> section.

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 EmployeeBean getChange(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();

ResultSet rs = stm.executeQuery(sql);

if(rs.next()) {

bean.setName(rs.getString("employeename"));

bean.setAddress(rs.getString("address"));

}

}catch(Exception ex){ ex.printStackTrace(); }

}

return bean;

}

}

EmployeeBean.javapackage 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)

<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);

WEB-INF/web.xml

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

L/O/G/Owww.themegallery.com

Thank You!SweNz FiXed

top related