DWR – Easy Ajax for Java

Download Report

Transcript DWR – Easy Ajax for Java

DWR – Easy Ajax for Java
Ivanka Todorova
April 4, 2007
1
Acknowledgements
• 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
2
Topics
• 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
3
What is DWR?
4
What 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
That’s why it is called “Direct remoting”
5
Why 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
6
1. 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.
7
2. 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.
8
DWR 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
9
Steps for Building DWR-based AJAX
Application
10
Steps
1. 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
2. Edit web.xml in the WEB-INF directory
 add servlet and servlet mapping information
3. 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
11
Step #2 Edit web.xml in the WEBINF directory
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name><paramvalue>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
12
Step#3 Create dwr.xml file in the
WEB-INF directory
• The example below creates a JavaScript
class “JDate” matching the Java class
“java.util.Date”
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct
Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd"> <dwr>
<allow>
<create creator="new" javascript="JDate"> <param
name="class" value="java.util.Date"/> </create>
</allow>
</dwr>
13
Test and Deploy the Application
•
•
•
Go to the following URL:
http://localhost:8088/[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.
14
Registering Callback Functions for
AJAX-based Asynchronous
Invocation
15
How 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
16
1. 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);
}
17
2. 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, {
callback:function(str) { alert(str); },
timeout:5000,
errorHandler:function(message) { alert("Oops: " + message); } });
18
Finding 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.
19
1. 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 ...
}
20
2. Creating JavaScript objects to
Match Java objects
• Then you can call this from JavaScript like
this:
var p = {
name:"Fred Bloggs",
age:42,
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.
21
Converters
22
Types 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
23
Basic 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 <convert> element in
the <allow>section 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
24
1. 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 following:
<convert converter="bean" match="your.full.package.BeanName"/>
• To allow conversion of any class in the given
package, or sub package:
<convert converter="bean" match="your.full.package.*"/>
25
2. 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", age:21 };
Remoted.setPerson(p);
26
3. 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 :
<convert converter="bean" match="com.example.Fred">
<param name="exclude" value="property1, property2"/>
</convert>
• 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:
<convert converter="bean" match="com.example.Fred">
<param name="include" value="property1, property2"/>
</convert>
• Good security design commonly involves
white-listing rather than black-listing.
27
Collection Converters
• The final two default converters are for maps
and collections:
•
<convert converter="collection" match="java.util.Collection"/> and
<convert converter="map" match="java.util.Map"/>
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.
28
1. 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:
<convert converter="enum" match="your.full.package.EnumName"/>
• Setting up JavaScript variables
public class Remoted {
public void setStatus(Status p) {
// ...
}
}
enum Status {
PASS,
FAIL,
}
29
2. 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.
30
DOM 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.
31
1. 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.
32
2. 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.
33
Creators
34
1. Creators
• The create element in your dwr.xml file has the following
structure.
•
•
<allow>
<create creator="..." javascript="..." scope="...">
<param name="..." value="..."/>
<auth method="..." role="..."/>
<exclude method="..."/>
<include method="..."/>
</create>
...
</allow>
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.
35
2. 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
<create creator="new" javascript="Fred">
<param name="class" value="com.example.Fred"/>
<auth method="setHourlyPay" role="admin"/>
</create>
36
3. Creators
•
•
•
The new creator is declared by default by DWR as follows: <creator
id="new" class="uk.ltd.getahead.dwr.create.NewCreator"/>. 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:
<allow>
<create creator="new" javascript=“Date">
<param name="class" value="java.util.Date"/>
</create>
...
</allow>
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).
37
Creators 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 r=Remote.method (param, callback)
creator
converter
38
Utility Functions
39
1. 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
40
2. 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
41
1. 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/ajaxdwrintro/
 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-062005/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.
42
2. 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://www128.ibm.com/developerworks/java/library/jajax3/
•
 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!
43