Title: DWR
1DWR Easy Ajax for Java
- Ivanka Todorova
- April 4, 2007
2Acknowledgements
- These slides are created from contents from DWR
web site http//getahead.org/dwr - Many slides are based on
- Sang Shin. Introduction to DWR (Direct Web
Remoting). Retrieved April 1, 2007 on the World
Wide Web http//www.javapassion.com/ajax/DWR.pdf
3Topics
- What is DWR?
- Steps for building DWR-based AJAX application
- Registering callback functions
- Converters
- Creators
- Utility functions
- Additional Resources with Coding Examples of DWR
Applications
4What is DWR?
5What is DWR?
- Consists of a server-side Java libraries, a DWR
servlet, and JavaScript libraries that allow you
to write Ajax web applications - Hides low-level XMLHttpRequest Handling
- Specifically designed with Java technology in
mind - Easy Ajax for Java
- Allows JavaScript code in a browser to use Java
functions running on a web server as if they were
in the browser - Thats why it is called Direct remoting
6Why DWR?
- Without DWR, you would have to create many Web
application endpoints (servlets) that need to be
addressable via URIs - If you have several methods in a class on the
server that you want to invoke from the browser - Each of these methods need to be addressable via
URI - You would have to map parameters and return
values to HTML input form parameters and
responses yourself - DWR comes with some JavaScript utility functions
71. How Does DWR Work?
- DWR dynamically generates a matching client-side
JavaScript class from a backend Java class - Allows you to write JavaScript code that looks
like conventional RPC/RMI code - The generated JavaScript class handles remoting
details between the browser and the backend
server - Handles asynchronous communication via
XMLHttpRequest by invoking the callback function
in the JavaScript - You provide the callback function as additional
parameter - DWR converts all the parameters and return values
between client-side JavaScript and backend Java.
82. How DWR Works
- DWR dynamically generates an AjaxService class
in Javascript to match some server-side code.
This is called by the eventHandler. DWR then
handles all the remoting details, including
converting all the parameters and return values
between Javascript and Java. It then executes
the supplied callback function (populateList)
which uses a DWR utility function to alter the
web page.
9DWR Consists of Two Main Parts
- A Java Servlet running on the server that
processes requests and sends responses back to
the browser. - uk.ltd.getahead.dwr.DWRServlet
- This servlet delegates the call to the backend
class you specify in the dwr.xml configuration
file - JavaScript running in the browser that sends
requests and can dynamically update the webpage. - DWR handles XMLHttpRequest handling
10Steps for Building DWR-based AJAX Application
11Steps
- Download the dwr.jar file and place it in the
WEB-INF/lib directory of your webapp - dwr.jar contains DWR runtime code including the
DWR servlet - Edit web.xml in the WEB-INF directory
- add servlet and servlet mapping information
- Create dwr.xml file in the WEB-INF directory
- You specify classes and methods DWR can create
and remote for use by client-side JavaScript code
12Step 2 Edit web.xml in the WEB-INF directory
- ltservletgt
- ltservlet-namegtdwr-invokerlt/servlet-namegt
- ltdisplay-namegtDWR Servletlt/display-namegt
- ltservlet-classgtuk.ltd.getahead.dwr.DWRServletlt/se
rvlet-classgt - ltinit-paramgt
- ltparam-namegtdebuglt/param-namegtltparam-valuegttruelt/p
aram-valuegt - lt/init-paramgt
- lt/servletgt
- ltservlet-mappinggt
- ltservlet-namegtdwr-invokerlt/servlet-namegt
- lturl-patterngt/dwr/lt/url-patterngt
- lt/servlet-mappinggt
13Step3 Create dwr.xml file in the WEB-INF
directory
- The example below creates a JavaScript class
JDate matching the Java class java.util.Date - lt!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD
Direct Web Remoting 1.0//EN" "http//www.getahead.
ltd.uk/dwr/dwr10.dtd"gt ltdwrgt - ltallowgt
- ltcreate creator"new" javascript"JDate"gt ltparam
name"class" value"java.util.Date"/gt lt/creategt - lt/allowgt
- lt/dwrgt
14Test and Deploy the Application
- Go to the following URL http//localhost8088/
YOUR-WEBAPP/dwr/ - You should see a page showing you the classes
that you've selected and an index of all the
methods known to DWR. - NETBEANS IDE 5.5 TROUBLESHOOTING TIP
- You may choose a different port number
- If you run your code multiple times and get the
message Server Port Already in Use in go to
Tools, Server Manager and change the port number.
15Registering Callback Functions for AJAX-based
Asynchronous Invocation
16How DWR Handles Asynchronous AJAX Call
- Calling JavaScript function at the client needs
to be done asynchronously while calling a Java
method (at the server) is synchronous - DWR has to handle this mismatch
- DWR provides a scheme for registering a callback
function at the client - This callback function is called when the data is
returned from the server this is AJAX behavior - You pass the callback function as an additional
parameter
171. How the Callback Function is Registered
- Suppose we have a Java method that looks like
this - //Server side Java code
- public class MyRemoteJavaClass
- public String getData(int index)
-
- We can use this from JavaScript as follows
- //Callback function to be called
- function handleGetData(str)
- alert(str)
-
182. How the Callback Function is Registered
- The callback function is passed as an additional
parameter - MyRemoteJavaScriptClass.getData(42,
handleGetData) - Alternatively you can use the all-in-one-line
version - Remote.getData(42, function(str) alert(str)
) - Or we can use a call meta-data object that
specifies the callback function - Remote.getData(42, callback function(str)
alert(str) ) - In addition to the callback metadata you can also
specify a timeout and an error handler - Remote.getData(42,
- callbackfunction(str) alert(str) ,
- timeout5000,
- errorHandlerfunction(message) alert("Oops "
message) )
19Finding the Callback Method
- If there is a function first or last then this is
the callback function - If the first parameter is null we assume that
there is no callback function. We check to see
that the last param is not null and give a
warning if it is. - If the last param is null, then there is no
callback function.
201. Creating JavaScript objects to Match Java
objects
- Suppose you have an exposed Java method like
this - public class Remote
- public void setPerson(Person p)
- this.person p
-
-
- And Person looks like this
- public Person
- private String name
- private int age
- private Date appointments
- // getters and setters ...
-
212. Creating JavaScript objects to Match Java
objects
- Then you can call this from JavaScript like this
- var p
- name"Fred Bloggs",
- age42,
- appointments new Date(), new Date("1 Jan
2008") -
- Remote.setPerson(p)
- Any fields missing from the JavaScript
representation will be left unset in the Java
version.
22Converters
23Types of Converters
- A converter converts data between the client and
the server - Types of converters provided by DWR
- Basic Converters
- Bean and Object Converters
- Enum Converters
- Collection Converter
- DOM Objects
- Servlet Objects (HttpServletRequest, HttpSession,
etc.) - While you can create your own converters this is
rarely needed
24Basic Converters
- Handle
- Boolean, byte, short, int, long, float, double,
char, java.lang.Boolean, java.lang. byte,
java.lang.Short, java.lang.Integer,
java.lang.Long, java.lang.Float,
java.lang.Double, java.lang.Character,
java.math.BigInteger, java.math.BigDecimal and
java.lang.String - No need to have a ltconvertgt element in the
ltallowgtsection in dwr.xml to use them. - They are enabled by default
- A Date Converter converts data between a
JavaScript date and a java.util.Date,
java.sql.Date, java.sql.Times, or, java.sql.
Timestamp
251. Bean and Object Converters
- The Bean converter converts Plain Old Java
Objects (POJOs) into JavaScript Associative
arrays and back again. - The Object converter is similar except that it
works on object members directly rather than
through getters and setters. - You can enable the bean converter for a single
class using the followingltconvert
converter"bean" match"your.full.package.BeanName
"/gt - To allow conversion of any class in the given
package, or sub package ltconvert
converter"bean" match"your.full.package."/gt
262. Bean and Object Converters
- DWR will convert Javascript objects (aka maps,
aka associative arrays) into Java beans or Java
objects. - public class Remoted
- public void setPerson(Person p)
- // ...
-
-
- public class Person
- public void setName(String name) ...
- public void setAge(int age) ...
- // ...
-
- If Remoted was configured as a Creator, and
Person is convertible using the Bean Converter,
then you can call the Java code as follows - var p name"Fred", age21
- Remoted.setPerson(p)
273. Bean and Object Converters
- Restricting Property Conversions
- Just as you have exclude and include for
creators to instruct DWR to exclude methods,
there is a similar system for Bean Converters - ltconvert converter"bean" match"com.example.Fred
"gt - ltparam name"exclude" value"property1,
property2"/gt - lt/convertgt
- This will ensure that DWR does not call
fred.getProperty1() and fred.getProperty2. - Alternatively if you prefer to white-list rather
than black-list you can do the following - ltconvert converter"bean" match"com.example.Fred"
gt - ltparam name"include" value"property1,
property2"/gt - lt/convertgt
- Good security design commonly involves
white-listing rather than black-listing.
28Collection Converters
- The final two default converters are for maps and
collections - ltconvert converter"collection"
match"java.util.Collection"/gt and - ltconvert converter"map" match"java.util.Map"/gt
- Generally speaking these converters will be able
to recursively convert their contents. - The two converters above can convert from any
collection to something meaningful in JavaScript,
however there is no way to know what sort of
Collection to convert to going the other way. - Since we can't work it out automatically we may
need to use the special signatures syntax in the
dwr.xml file to allow us to hint types to the
conversion process.
291. Enum Converters
- Converts Java5 Enums into JavaScript strings and
back again. Not enabled by default. - You can enable the Enum Converter for a single
class using the following - ltconvert converter"enum" match"your.full.package
.EnumName"/gt -
- Setting up JavaScript variables
- public class Remoted
- public void setStatus(Status p)
- // ...
-
-
- enum Status
- PASS,
- FAIL,
-
302. Enum Converter
- If Remoted was configured as a Creator, and
Status is convertible using the EnumConverter,
then you can call the Java code from JavaScript
as follows Remoted.setStatus("PASS") - If no match is found in the given enum, then an
exception will be thrown.
31DOM Objects
- DWR automatically converts DOM trees from DOM,
DOM4J, JDOM and XOM. -
- You simply return a Document, Element or Node
from any of the above and DWR will automatically
convert it into a browser DOM object.
321. Servlet Objects
- There are only 2 Java classes that you commonly
need to depend on within DWR as a user -
WebContext and WebContextFactory. - These classes give you access to the standard
HTTP servlet objects HttpServletRequest ,
HttpServletResponse, HttpSession,
ServletContext, and ServletConfig - It is important that you treat the HTTP request
and response as read only. Any attempt to change
the HTTP body will cause DWR errors.
332. Servlet Objects
- The alternative method is to access the HTTP
servlet objects without writing code that depends
on DWR just have the needed parameter declared
on your code. - For example if you have remoted a class like
this - public class Remote
- public void method (int param,
ServletContext cx, String s) ... -
- Then you will be able to access it from
Javascript just as though the ServletContext
parameter was not there - Remote.method(42, "test", callback)
- Make sure you are not using the callback function
as first parameter, instead use the callback as
last parameter.
34Creators
351. Creators
- The create element in your dwr.xml file has the
following structure. - ltallowgt
- ltcreate creator"..." javascript"..."
scope"..."gt - ltparam name"..." value"..."/gt
- ltauth method"..." role"..."/gt
- ltexclude method"..."/gt
- ltinclude method"..."/gt
- lt/creategt
- ...
- lt/allowgt
- Most of these elements are optional. All you
really need is to specify a creator and a
JavaScript name. The creator attribute is
required it specifies which creator will be
used. - The javascript attribute gives your newly created
object a name in the browser.
362. Creators
- The scope attribute is optional. It defaults to
page. The other options are application,
session, and request. - The param attribute is used by the various
creators for specific bits of configuration. For
example the 'new' creator needs to be told what
type of object to call 'new' on. - The include and exclude elements allow a creator
to restrict access to class methods. A Creator
should specify EITHER a list of include elements
(which implies that the default policy is denial)
OR a list of exclude elements (which implies that
the default policy is to allow access). - For example to deny access to all methods in some
class except for the setHourlyPay() method you
should put the following into your dwr.xml - ltcreate creator"new" javascript"Fred"gt
- ltparam name"class" value"com.example.Fred"/gt
- ltauth method"setHourlyPay" role"admin"/gt
- lt/creategt
373. Creators
- The new creator is declared by default by DWR as
follows ltcreator id"new" class"uk.ltd.getahead.
dwr.create.NewCreator"/gt. It creates an instance
of a class using the default constructor. - You allow DWR to use the new creator to create
and remote your beans as follows - ltallowgt
- ltcreate creator"new" javascriptDate"gt
- ltparam name"class" value"java.util.Date"/gt
- lt/creategt
- ...
- lt/allowgt
- This remotes java.util.Date to Javascript and
gives it the name Date so in Javascript when you
call Date.toString(reply) then a new
java.util.Date will be constructed using the
default constructor, then the toString() method
will be called, and the data returned to the
javascript reply function (in this case the
current date in string form). -
38Creators and Converters Summary
- Creators create objects that live on the server
and have their methods remoted - Converters convert parameters and return types
- Created objects do things while converted objects
carry data - var rRemote.method (param, callback)
creator
converter
39Utility Functions
401. Utility Functions
- The util.js contains utility functions to help
you update your web pages with JavaScript data - You can even use it outside of DWR because it
does not depend on DWR to function - Some of the available utility functions are
- (id)
- getValue, getValues, setValue, setValues
- addRows and removeAllRows
412. Utility Functions
- (id) is the same as
- Document.getElementById(id) in DOM API
- DWRUtil.getValue(id) get the value(s) out of the
HTML elements - DWRUtil.setValue(id, value) finds the element
with the id in the first parameter and alters its
contents to the second parameter
421. Tutorials and Articles about DWR
- DWR Hands-on Lab by Sang Shin, Sun Microsystems.
Retrieved April 3, 2007 from the World Wide Web
http//www.javapassion.com/handsonlabs/ajaxdwrintr
o/ - Contains full code for four applications Chat,
Populating Selection List, Form Editing, and
Table Editing. - AJAX made simple with DWR by Cloves Carneiro
Jr., JavaWorld.com, 06/20/05. Retrieved April 3,
2007 from the World Wide Web http//www.javaworld
.com/javaworld/jw-06-2005/jw-0620-dwr.html - The example application used in this article
simulates an apartment rental search engine for
the city of Toronto. The user can select a set of
search criteria before performing the search.
432. Tutorials and Articles about DWR
- Ajax for Java developers Ajax with Direct Web
Remoting by Philip McCarthy. Retrieved April 3,
2007 from the World Wide Web http//www-128.ibm.c
om/developerworks/java/library/j-ajax3/ - Includes implementation of a shopping cart
- Extensive list of tutorials and articles about
DWR. Retrieved April 3, 2007 from the World Wide
Web http//getahead.org/dwr/elsewhere Definitely
worth visiting!