43
1 DWR – Easy Ajax for DWR – Easy Ajax for Java Java Ivanka Todorova Ivanka Todorova April 4, 2007 April 4, 2007

DWR – Easy Ajax for Java

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: DWR – Easy Ajax for Java

11

DWR – Easy Ajax for JavaDWR – Easy Ajax for Java

Ivanka TodorovaIvanka Todorova

April 4, 2007April 4, 2007

Page 2: DWR – Easy Ajax for Java

22

AcknowledgementsAcknowledgements• These slides are created from contents These slides are created from contents

from DWR web site from DWR web site http://getahead.org/dwrhttp://getahead.org/dwr

• Many slides are based on:Many slides are based on:Sang Shin. Sang Shin. Introduction to DWR (Direct Introduction to DWR (Direct

Web Remoting). Web Remoting). Retrieved April 1, 2007 on Retrieved April 1, 2007 on the World Wide Web: the World Wide Web: http://www.javapassion.com/ajax/DWR.pdfhttp://www.javapassion.com/ajax/DWR.pdf

Page 3: DWR – Easy Ajax for Java

33

TopicsTopics• What is DWR?What is DWR?

• Steps for building DWR-based AJAX Steps for building DWR-based AJAX applicationapplication

• Registering callback functionsRegistering callback functions

• ConvertersConverters

• CreatorsCreators

• Utility functionsUtility functions

• Additional Resources with Coding Additional Resources with Coding Examples of DWR ApplicationsExamples of DWR Applications

Page 4: DWR – Easy Ajax for Java

44

What is DWR?What is DWR?

Page 5: DWR – Easy Ajax for Java

55

What is DWR?What is DWR?• Consists of a server-side Java libraries, Consists of a server-side Java libraries,

a DWR servlet, and JavaScript libraries a DWR servlet, and JavaScript libraries that allow you to write Ajax web that allow you to write Ajax web applicationsapplicationsHides low-level XMLHttpRequest HandlingHides low-level XMLHttpRequest Handling

• Specifically designed with Java Specifically designed with Java technology in mindtechnology in mind““Easy Ajax for Java”Easy Ajax for Java”

• Allows JavaScript code in a browser to Allows JavaScript code in a browser to use Java functions running on a web use Java functions running on a web server as if they were in the browserserver as if they were in the browserThat’s why it is called “Direct remoting”That’s why it is called “Direct remoting”

Page 6: DWR – Easy Ajax for Java

66

Why DWR?Why DWR?• Without DWR, you would have to create Without DWR, you would have to create

many Web application endpoints (servlets) many Web application endpoints (servlets) that need to be addressable via URIsthat need to be addressable via URIs

• If you have several methods in a class on If you have several methods in a class on the server that you want to invoke from the server that you want to invoke from the browserthe browser Each of these methods need to be addressable Each of these methods need to be addressable

via URIvia URI You would have to map parameters and return You would have to map parameters and return

values to HTML input form parameters and values to HTML input form parameters and responses yourselfresponses yourself

• DWR comes with some JavaScript utility DWR comes with some JavaScript utility functionsfunctions

Page 7: DWR – Easy Ajax for Java

77

1. How Does DWR Work? 1. How Does DWR Work? • DWR dynamically generates a matching DWR dynamically generates a matching

client-side JavaScript class from a backend client-side JavaScript class from a backend Java classJava class Allows you to write JavaScript code that looks like Allows you to write JavaScript code that looks like

conventional RPC/RMI codeconventional RPC/RMI code

• The generated JavaScript class handles The generated JavaScript class handles remoting details between the browser and remoting details between the browser and the backend serverthe backend server Handles asynchronous communication via Handles asynchronous communication via

XMLHttpRequest by invoking the callback function XMLHttpRequest by invoking the callback function in the JavaScriptin the JavaScript

You provide the callback function as additional You provide the callback function as additional parameterparameter

DWR converts all the parameters and return DWR converts all the parameters and return values between client-side JavaScript and backend values between client-side JavaScript and backend Java. Java.

Page 8: DWR – Easy Ajax for Java

88

2. How DWR Works2. How DWR WorksDWR dynamically generates an AjaxService class in Javascript to DWR dynamically generates an AjaxService class in Javascript to match some server-side code. This is called by the eventHandler. match some server-side code. This is called by the eventHandler. DWR then handles all the remoting details, including converting all DWR then handles all the remoting details, including converting all the parameters and return values between Javascript and Java. the parameters and return values between Javascript and Java. It then executes the supplied callback function (populateList) which It then executes the supplied callback function (populateList) which uses a DWR utility function to alter the web page. uses a DWR utility function to alter the web page.

Page 9: DWR – Easy Ajax for Java

99

DWR Consists of Two Main DWR Consists of Two Main PartsParts

•A Java Servlet running on the server A Java Servlet running on the server that processes requests and sends that processes requests and sends responses back to the browser.responses back to the browser. uk.ltd.getahead.dwr.DWRServletuk.ltd.getahead.dwr.DWRServlet This servlet delegates the call to the backend This servlet delegates the call to the backend

class you specify in the dwr.xml configuration class you specify in the dwr.xml configuration filefile

• JavaScript running in the browser that JavaScript running in the browser that sends requests and can dynamically sends requests and can dynamically update the webpage.update the webpage.DWR handles XMLHttpRequest handlingDWR handles XMLHttpRequest handling

Page 10: DWR – Easy Ajax for Java

1010

Steps for Building DWR-based Steps for Building DWR-based AJAX ApplicationAJAX Application

Page 11: DWR – Easy Ajax for Java

1111

StepsSteps

1.1. Download the dwr.jar file and place it in Download the dwr.jar file and place it in the WEB-INF/lib directory of your webappthe WEB-INF/lib directory of your webapp

dwr.jar contains DWR runtime code including the DWR dwr.jar contains DWR runtime code including the DWR servletservlet

2.2. Edit web.xml in the WEB-INF directoryEdit web.xml in the WEB-INF directory add servlet and servlet mapping informationadd servlet and servlet mapping information

3.3. Create dwr.xml file in the WEB-INF Create dwr.xml file in the WEB-INF directorydirectory

You specify classes and methods DWR can create and You specify classes and methods DWR can create and remote for use by client-side JavaScript coderemote for use by client-side JavaScript code

Page 12: DWR – Easy Ajax for Java

1212

Step #2 Edit web.xml in the Step #2 Edit web.xml in the WEB-INF directoryWEB-INF directory

<servlet><servlet> <servlet-name>dwr-invoker</servlet-name><servlet-name>dwr-invoker</servlet-name> <display-name>DWR Servlet</display-name><display-name>DWR Servlet</display-name> <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-

class>class> <init-param><init-param><param-name>debug</param-name><param-<param-name>debug</param-name><param-

value>true</param-value>value>true</param-value></init-param></init-param> </servlet></servlet>

<servlet-mapping><servlet-mapping> <servlet-name>dwr-invoker</servlet-name><servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> <url-pattern>/dwr/*</url-pattern> </servlet-mapping></servlet-mapping>

Page 13: DWR – Easy Ajax for Java

1313

Step#3 Create dwr.xml file in Step#3 Create dwr.xml file in the WEB-INF directorythe WEB-INF directory• The example below creates a The example below creates a

JavaScript class “JDate” matching the JavaScript class “JDate” matching the Java class “java.util.Date”Java class “java.util.Date”

<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd"> "http://www.getahead.ltd.uk/dwr/dwr10.dtd"> <dwr><dwr>

<allow> <allow> <create creator="new" javascript="JDate"> <param <create creator="new" javascript="JDate"> <param

name="class" value="java.util.Date"/> </create>name="class" value="java.util.Date"/> </create></allow> </allow> </dwr></dwr>

Page 14: DWR – Easy Ajax for Java

1414

Test and Deploy the Test and Deploy the Application Application • Go to the following URL: Go to the following URL:

http://localhost:8088/http://localhost:8088/[YOUR-WEBAPP][YOUR-WEBAPP]/dwr/ /dwr/

• You should see a page showing you the You should see a page showing you the classes that you've selected and an index classes that you've selected and an index of all the methods known to DWR.of all the methods known to DWR.

• NETBEANS IDE 5.5NETBEANS IDE 5.5 TROUBLESHOOTING TIP TROUBLESHOOTING TIP You may choose a different port number You may choose a different port number If you run your code multiple times and get the If you run your code multiple times and get the

message “Server Port Already in Use” in go to message “Server Port Already in Use” in go to Tools, Server Manager and change the port Tools, Server Manager and change the port number. number.

Page 15: DWR – Easy Ajax for Java

1515

Registering Callback Functions Registering Callback Functions for AJAX-based Asynchronous for AJAX-based Asynchronous InvocationInvocation

Page 16: DWR – Easy Ajax for Java

1616

How DWR Handles How DWR Handles Asynchronous AJAX CallAsynchronous AJAX Call• Calling JavaScript function at the client Calling JavaScript function at the client

needs to be done asynchronously while needs to be done asynchronously while calling a Java method (at the server) is calling a Java method (at the server) is synchronoussynchronous DWR has to handle this mismatchDWR has to handle this mismatch

• DWR provides a scheme for registering a DWR provides a scheme for registering a callback function at the clientcallback function at the client This callback function is called when the data is This callback function is called when the data is

returned from the server – this is AJAX behaviorreturned from the server – this is AJAX behavior You pass the callback function as an additional You pass the callback function as an additional

parameterparameter

Page 17: DWR – Easy Ajax for Java

1717

1. How the Callback Function is 1. How the Callback Function is RegisteredRegistered•Suppose we have a Java method Suppose we have a Java method

that looks like this:that looks like this://Server side Java code//Server side Java codepublic class MyRemoteJavaClass{public class MyRemoteJavaClass{ public String getData(int index){…}public String getData(int index){…}}}

•We can use this from JavaScript We can use this from JavaScript as followsas follows//Callback function to be called//Callback function to be calledfunction handleGetData(str) {function handleGetData(str) { alert(str);alert(str); } }

Page 18: DWR – Easy Ajax for Java

1818

2. How the Callback Function is 2. How the Callback Function is RegisteredRegistered• The callback function is passed as an additional The callback function is passed as an additional

parameterparameterMyRemoteJavaScriptClass.getData(42, handleGetData);MyRemoteJavaScriptClass.getData(42, handleGetData);

• Alternatively you can use the all-in-one-line version Alternatively you can use the all-in-one-line version Remote.getData(42, function(str) { alert(str); }); Remote.getData(42, function(str) { alert(str); });

• Or we can use a call meta-data object that specifies Or we can use a call meta-data object that specifies the callback functionthe callback functionRemote.getData(42, { callback: function(str) { alert(str); } }); Remote.getData(42, { callback: function(str) { alert(str); } });

• In addition to the callback metadata you can also In addition to the callback metadata you can also specify a timeout and an error handlerspecify a timeout and an error handlerRemote.getData(42, { Remote.getData(42, {

callback:function(str) { alert(str); }, callback:function(str) { alert(str); },

timeout:5000, timeout:5000,

errorHandler:function(message) { alert("Oops: " + errorHandler:function(message) { alert("Oops: " + message); } });message); } });

Page 19: DWR – Easy Ajax for Java

1919

Finding the Finding the CallbackCallback Method Method• If there is a function first or last then If there is a function first or last then

this is the callback function this is the callback function

• If the first parameter is null we If the first parameter is null we assume that there is no callback assume that there is no callback function. We check to see that the function. We check to see that the last param is not null and give a last param is not null and give a warning if it is. warning if it is.

• If the last param is null, then there is If the last param is null, then there is no callback function. no callback function.

Page 20: DWR – Easy Ajax for Java

2020

1. Creating JavaScript 1. Creating JavaScript objects to Match Java objectsobjects to Match Java objects• Suppose you have an exposed Java method like Suppose you have an exposed Java method like

this:this:public class Remote {public class Remote {

public void setPerson(Person p) { public void setPerson(Person p) {

this.person = p;this.person = p;

}}

} }

• And Person looks like this:And Person looks like this:public Person { public Person {

private String name; private String name;

private int age; private int age;

private Date[] appointments;private Date[] appointments;

// getters and setters ...// getters and setters ...

}}

Page 21: DWR – Easy Ajax for Java

2121

2. Creating JavaScript objects 2. Creating JavaScript objects to Match Java objectsto Match Java objects• Then you can call this from Then you can call this from

JavaScript like this:JavaScript like this:var p = {var p = {

name:"Fred Bloggs", name:"Fred Bloggs",

age:42, age:42,

appointments:[ new Date(), new Date("1 Jan 2008") ]appointments:[ new Date(), new Date("1 Jan 2008") ]

}; };

Remote.setPerson(p); Remote.setPerson(p);

• Any fields missing from the Any fields missing from the JavaScript representation will be left JavaScript representation will be left unset in the Java version.unset in the Java version.

Page 22: DWR – Easy Ajax for Java

2222

ConvertersConverters

Page 23: DWR – Easy Ajax for Java

2323

Types of ConvertersTypes of Converters• A converter converts data between A converter converts data between

the client and the serverthe client and the server

• Types of converters provided by Types of converters provided by DWRDWR Basic ConvertersBasic Converters Bean and Object ConvertersBean and Object Converters Enum ConvertersEnum Converters Collection ConverterCollection Converter DOM ObjectsDOM Objects Servlet Objects (HttpServletRequest, HttpSession, etc.)Servlet Objects (HttpServletRequest, HttpSession, etc.)

• While you can create your own While you can create your own converters this is rarely neededconverters this is rarely needed

Page 24: DWR – Easy Ajax for Java

2424

Basic ConvertersBasic Converters• HandleHandle

Boolean, byte, short, int, long, float, double, char, Boolean, byte, short, int, long, float, double, char, java.lang.Boolean, java.lang. byte, java.lang.Short, java.lang.Boolean, java.lang. byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.lang.Character, java.math.BigInteger, java.lang.Double, java.lang.Character, java.math.BigInteger, java.math.BigDecimal and java.lang.Stringjava.math.BigDecimal and java.lang.String

• No need to have a <convert> element No need to have a <convert> element in the <allow>section in dwr.xml to use in the <allow>section in dwr.xml to use them. them. They are enabled by defaultThey are enabled by default

• A Date Converter converts data A Date Converter converts data between a JavaScript date and a between a JavaScript date and a java.util.Date, java.sql.Date, java.util.Date, java.sql.Date, java.sql.Times, or, java.sql. Timestamp java.sql.Times, or, java.sql. Timestamp

Page 25: DWR – Easy Ajax for Java

2525

1. Bean and Object Converters1. Bean and Object Converters

• The Bean converter converts Plain Old Java The Bean converter converts Plain Old Java Objects (POJOs) into JavaScript Associative Objects (POJOs) into JavaScript Associative arrays and back again.arrays and back again.

• The Object converter is similar except that The Object converter is similar except that it works on object members directly rather it works on object members directly rather than through getters and setters.than through getters and setters.

• You can enable the bean converter for a You can enable the bean converter for a single class using the following:single class using the following:<convert converter="bean" <convert converter="bean" match="your.full.package.BeanName"/>match="your.full.package.BeanName"/>

• To allow conversion of any class in the To allow conversion of any class in the given package, or sub package: given package, or sub package: <convert converter="bean" match="your.full.package.*"/><convert converter="bean" match="your.full.package.*"/>

Page 26: DWR – Easy Ajax for Java

2626

2. Bean and Object Converters2. Bean and Object Converters• DWR will convert Javascript objects (aka maps, aka DWR will convert Javascript objects (aka maps, aka

associative arrays) into Java beans or Java objects.associative arrays) into Java beans or Java objects.public class Remoted {public class Remoted {

public void setPerson(Person p) {public void setPerson(Person p) {

// ... // ...

}}

} }

public class Person { public class Person {

public void setName(String name) { ... } public void setName(String name) { ... }

public void setAge(int age) { ... } public void setAge(int age) { ... }

// ...// ...

} }

• If Remoted was configured as a Creator, and If Remoted was configured as a Creator, and Person is convertible using the Bean Converter, Person is convertible using the Bean Converter, then you can call the Java code as follows:then you can call the Java code as follows:

var p = { name:"Fred", age:21 };var p = { name:"Fred", age:21 };

Remoted.setPerson(p); Remoted.setPerson(p);

Page 27: DWR – Easy Ajax for Java

2727

3. Bean and Object Converters3. Bean and Object Converters• Restricting Property ConversionsRestricting Property Conversions

Just as you have exclude and include for creators to instruct DWR Just as you have exclude and include for creators to instruct DWR to exclude methods, there is a similar system for Bean Converters to exclude methods, there is a similar system for Bean Converters ::<convert converter="bean" match="com.example.Fred"><convert converter="bean" match="com.example.Fred"><param name="exclude" value="property1, property2"/><param name="exclude" value="property1, property2"/></convert> </convert>

• This will ensure that DWR does not call This will ensure that DWR does not call fred.getProperty1() and fred.getProperty2.fred.getProperty1() and fred.getProperty2.

• Alternatively if you prefer to white-list Alternatively if you prefer to white-list rather than black-list you can do the rather than black-list you can do the following:following: <convert converter="bean" match="com.example.Fred"> <convert converter="bean" match="com.example.Fred"> <param name="include" value="property1, property2"/><param name="include" value="property1, property2"/></convert></convert>

• Good security design commonly involves Good security design commonly involves white-listing rather than black-listing.white-listing rather than black-listing.

Page 28: DWR – Easy Ajax for Java

2828

Collection ConvertersCollection Converters• The final two default converters are for maps The final two default converters are for maps

and collections:and collections:<convert converter="collection" match="java.util.Collection"/> <convert converter="collection" match="java.util.Collection"/>

andand<convert converter="map" match="java.util.Map"/><convert converter="map" match="java.util.Map"/>

• Generally speaking these converters will be Generally speaking these converters will be able to recursively convert their contents. able to recursively convert their contents.

• The two converters above can convert from The two converters above can convert from any collection to something meaningful in any collection to something meaningful in JavaScript, however there is no way to know JavaScript, however there is no way to know what sort of Collection to convert to going the what sort of Collection to convert to going the other way. other way.

• Since we can't work it out automatically we Since we can't work it out automatically we may need to use the special signatures syntax may need to use the special signatures syntax in the dwr.xml file to allow us to hint types to in the dwr.xml file to allow us to hint types to the conversion process. the conversion process.

Page 29: DWR – Easy Ajax for Java

2929

1. Enum Converters1. Enum Converters• Converts Java5 Enums into JavaScript Converts Java5 Enums into JavaScript

strings and back again. Not enabled by strings and back again. Not enabled by default. default.

• You can enable the Enum Converter for a You can enable the Enum Converter for a single class using the following:single class using the following:<convert converter="enum" <convert converter="enum"

match="your.full.package.EnumName"/>match="your.full.package.EnumName"/>

• Setting up JavaScript variablesSetting up JavaScript variables public class Remoted {public class Remoted {

public void setStatus(Status p) {public void setStatus(Status p) { // ... // ... }}} }

enum Status {enum Status { PASS, PASS, FAIL,FAIL, } }

Page 30: DWR – Easy Ajax for Java

3030

2. Enum Converter2. Enum Converter

• If Remoted was configured as a If Remoted was configured as a Creator, and Status is convertible Creator, and Status is convertible using the EnumConverter, then you using the EnumConverter, then you can call the Java code from can call the Java code from JavaScript as follows: JavaScript as follows: Remoted.setStatus("PASS");Remoted.setStatus("PASS");

• If no match is found in the given If no match is found in the given enum, then an exception will be enum, then an exception will be thrown. thrown.

Page 31: DWR – Easy Ajax for Java

3131

DOM ObjectsDOM Objects

• DWR automatically converts DOM DWR automatically converts DOM trees from DOM, DOM4J, JDOM and trees from DOM, DOM4J, JDOM and XOM.XOM.

• You simply return a Document, You simply return a Document, Element or Node from any of the Element or Node from any of the above and DWR will automatically above and DWR will automatically convert it into a browser DOM object. convert it into a browser DOM object.

Page 32: DWR – Easy Ajax for Java

3232

1. Servlet Objects1. Servlet Objects• There are only 2 Java classes that There are only 2 Java classes that

you commonly need to depend on you commonly need to depend on within DWR as a user - WebContext within DWR as a user - WebContext and WebContextFactory. and WebContextFactory.

• These classes give you access to the These classes give you access to the standard HTTP servlet objects: standard HTTP servlet objects: HttpServletRequest , HttpServletRequest , HttpServletResponse, HttpSession, HttpServletResponse, HttpSession, ServletContext, and ServletConfigServletContext, and ServletConfig

• It is important that you treat the It is important that you treat the HTTP request and response as read HTTP request and response as read only. Any attempt to change the only. Any attempt to change the HTTP body will cause DWR errors. HTTP body will cause DWR errors.

Page 33: DWR – Easy Ajax for Java

3333

2. Servlet Objects2. Servlet Objects• The alternative method is to access the The alternative method is to access the

HTTP servlet objects without writing code HTTP servlet objects without writing code that depends on DWR – just have the that depends on DWR – just have the needed parameter declared on your code. needed parameter declared on your code.

• For example if you have remoted a class For example if you have remoted a class like this:like this:

public class Remote { public class Remote { public void method (int param, ServletContext cx, public void method (int param, ServletContext cx,

String s) { ... }String s) { ... } } }

Then you will be able to access it from Javascript just as Then you will be able to access it from Javascript just as though the ServletContext parameter was not there:though the ServletContext parameter was not there:

Remote.method(42, "test", callback); Remote.method(42, "test", callback); • Make sure you are not using the callback Make sure you are not using the callback

function as first parameter, instead use function as first parameter, instead use the callback as last parameter. the callback as last parameter.

Page 34: DWR – Easy Ajax for Java

3434

CreatorsCreators

Page 35: DWR – Easy Ajax for Java

3535

1. Creators1. Creators• The create element in your dwr.xml file has the The create element in your dwr.xml file has the

following structure.following structure.<allow><allow> <create creator="..." javascript="..." scope="..."><create creator="..." javascript="..." scope="..."> <param name="..." value="..."/> <param name="..." value="..."/> <auth method="..." role="..."/> <auth method="..." role="..."/> <exclude method="..."/> <exclude method="..."/> <include method="..."/> <include method="..."/> </create></create> ......</allow></allow>

• Most of these elements are optional. All you really Most of these elements are optional. All you really need is to specify a creator and a JavaScript name. need is to specify a creator and a JavaScript name. The creator attribute is required – it specifies which The creator attribute is required – it specifies which creator will be used. creator will be used.

• The javascript attribute gives your newly created The javascript attribute gives your newly created object a name in the browser. object a name in the browser.

Page 36: DWR – Easy Ajax for Java

3636

2. Creators2. Creators • The The scope attributescope attribute is optional. It defaults to “page”. The is optional. It defaults to “page”. The

other options are “application”, “session”, and “request”. other options are “application”, “session”, and “request”. • The The param attributeparam attribute is used by the various creators for is used by the various creators for

specific bits of configuration. For example the 'new' creator specific bits of configuration. For example the 'new' creator

needs to be told what type of object to call 'new' on.needs to be told what type of object to call 'new' on. • TheThe include and exclude elements include and exclude elements allow a creator to allow a creator to

restrict access to class methods. A Creator should specify restrict access to class methods. A Creator should specify EITHER a list of include elements (which implies that the EITHER a list of include elements (which implies that the default policy is denial) OR a list of exclude elements (which default policy is denial) OR a list of exclude elements (which implies that the default policy is to allow access). implies that the default policy is to allow access).

• For example to deny access to all methods in some class For example to deny access to all methods in some class except for the setHourlyPay() method you should put the except for the setHourlyPay() method you should put the following into your dwr.xmlfollowing into your dwr.xml<create creator="new" javascript="Fred"><create creator="new" javascript="Fred"><param name="class" value="com.example.Fred"/><param name="class" value="com.example.Fred"/><auth method="setHourlyPay" role="admin"/> <auth method="setHourlyPay" role="admin"/> </create> </create>

Page 37: DWR – Easy Ajax for Java

3737

3. Creators3. Creators

• The The newnew creator is declared by default by DWR as follows: creator is declared by default by DWR as follows: <creator id="new" <creator id="new" class="uk.ltd.getahead.dwr.create.NewCreator"/>. class="uk.ltd.getahead.dwr.create.NewCreator"/>. It creates an It creates an instance of a class using the default constructor. instance of a class using the default constructor.

• You allow DWR to use the new creator to create and remote your You allow DWR to use the new creator to create and remote your beans as follows:beans as follows:<allow> <allow>

<create creator="new" javascript=“Date"> <create creator="new" javascript=“Date">

<param name="class" value="java.util.Date"/><param name="class" value="java.util.Date"/>

</create></create>

......

</allow></allow>

• This remotes java.util.Date to Javascript and gives it the name This remotes java.util.Date to Javascript and gives it the name Date so in Javascript when you call Date.toString(reply) then a Date so in Javascript when you call Date.toString(reply) then a new java.util.Date will be constructed using the default new java.util.Date will be constructed using the default constructor, then the toString() method will be called, and the constructor, then the toString() method will be called, and the data returned to the javascript reply function (in this case the data returned to the javascript reply function (in this case the current date in string form).current date in string form).

Page 38: DWR – Easy Ajax for Java

3838

Creators and Converters Creators and Converters SummarySummary• Creators create objects that live on Creators create objects that live on

the server and have their methods the server and have their methods remotedremoted

• Converters convert parameters and Converters convert parameters and return typesreturn types

• Created objects do things while Created objects do things while converted objects carry dataconverted objects carry datavar r=Remote.method (param, callback)var r=Remote.method (param, callback)creator converter

Page 39: DWR – Easy Ajax for Java

3939

Utility FunctionsUtility Functions

Page 40: DWR – Easy Ajax for Java

4040

1. Utility Functions 1. Utility Functions • The util.js contains utility functions to help The util.js contains utility functions to help

you update your web pages with you update your web pages with JavaScript dataJavaScript data

• You can even use it outside of DWR You can even use it outside of DWR because it does not depend on DWR to because it does not depend on DWR to functionfunction

• Some of the available utility functions are: Some of the available utility functions are: $(id)$(id)getValue, getValues, setValue, setValuesgetValue, getValues, setValue, setValuesaddRows and removeAllRowsaddRows and removeAllRows

Page 41: DWR – Easy Ajax for Java

4141

2. Utility Functions2. Utility Functions• $(id) is the same as $(id) is the same as

Document.getElementById(id) in DOM Document.getElementById(id) in DOM APIAPI

• DWRUtil.getValue(id) get the value(s) DWRUtil.getValue(id) get the value(s) out of the HTML elementsout of the HTML elements

• DWRUtil.setValue(id, value) finds the DWRUtil.setValue(id, value) finds the element with the id in the first element with the id in the first parameter and alters its contents to parameter and alters its contents to the second parameterthe second parameter

Page 42: DWR – Easy Ajax for Java

4242

1. Tutorials and Articles about 1. Tutorials and Articles about DWRDWR

• DWR Hands-on Lab by Sang Shin, Sun Microsystems. DWR Hands-on Lab by Sang Shin, Sun Microsystems. Retrieved April 3, 2007 from the World Wide Web: Retrieved April 3, 2007 from the World Wide Web: http://www.javapassion.com/handsonlabs/ajaxdwrinthttp://www.javapassion.com/handsonlabs/ajaxdwrintro/ro/ Contains full code for four applications: Chat, Populating Contains full code for four applications: Chat, Populating

Selection List, Form Editing, and Table Editing. Selection List, Form Editing, and Table Editing.

• AJAX made simple with DWR by Cloves Carneiro AJAX made simple with DWR by Cloves Carneiro Jr., JavaWorld.com, 06/20/05. Retrieved April 3, 2007 Jr., JavaWorld.com, 06/20/05. Retrieved April 3, 2007 from the World Wide Web: from the World Wide Web: http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-dwr.htmldwr.html The example application used in this article simulates an The example application used in this article simulates an

apartment rental search engine for the city of Toronto. The apartment rental search engine for the city of Toronto. The user can select a set of search criteria before performing user can select a set of search criteria before performing the search. the search.

Page 43: DWR – Easy Ajax for Java

4343

2. Tutorials and Articles about 2. Tutorials and Articles about DWRDWR• Ajax for Java developers: Ajax with Direct Ajax for Java developers: Ajax with Direct

Web Remoting by Philip McCarthy. Retrieved Web Remoting by Philip McCarthy. Retrieved April 3, 2007 from the World Wide Web: April 3, 2007 from the World Wide Web: http://www-128.ibm.com/developerworks/javhttp://www-128.ibm.com/developerworks/java/library/j-ajax3/a/library/j-ajax3/ Includes implementation of a shopping cartIncludes implementation of a shopping cart

• Extensive list of tutorials and articles about Extensive list of tutorials and articles about DWR. Retrieved April 3, 2007 from the World DWR. Retrieved April 3, 2007 from the World Wide Web: Wide Web: http://getahead.org/dwr/elsewherehttp://getahead.org/dwr/elsewhere Definitely Definitely worth visiting!worth visiting!