DWR Easy Ajax for Java Ivanka Todorova April

  • Slides: 43
Download presentation
DWR – Easy Ajax for Java Ivanka Todorova April 4, 2007 1

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

Acknowledgements • These slides are created from contents from DWR web site http: //getahead.

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

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

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

What is DWR? • Consists of a server-side Java libraries, a DWR servlet, and Java. Script libraries that allow you to write Ajax web applications ØHides low-level XMLHttp. Request Handling • Specifically designed with Java technology in mind Ø“Easy Ajax for Java” • Allows Java. Script 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

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 Java. Script utility functions 6

1. How Does DWR Work? • DWR dynamically generates a matching client-side Java. Script

1. How Does DWR Work? • DWR dynamically generates a matching client-side Java. Script class from a backend Java class Ø Allows you to write Java. Script code that looks like conventional RPC/RMI code • The generated Java. Script class handles remoting details between the browser and the backend server Ø Handles asynchronous communication via XMLHttp. Request by invoking the callback function in the Java. Script Ø You provide the callback function as additional parameter Ø DWR converts all the parameters and return values between client-side Java. Script and backend Java. 7

2. How DWR Works DWR dynamically generates an Ajax. Service class in Javascript to

2. How DWR Works DWR dynamically generates an Ajax. Service class in Javascript to match some server-side code. This is called by the event. Handler. 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 (populate. List) 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

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 • Java. Script running in the browser that sends requests and can dynamically update the webpage. ØDWR handles XMLHttp. Request handling 9

Steps for Building DWR-based AJAX Application 10

Steps for Building DWR-based AJAX Application 10

Steps 1. Download the dwr. jar file and place it in the WEB-INF/lib directory

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 Java. Script 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.

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

Step#3 Create dwr. xml file in the WEB-INF directory • The example below creates a Java. Script class “JDate” matching the Java class “java. util. Date” <!DOCTYPE dwr PUBLIC "-//Get. Ahead Limited//DTD Direct Web Remoting 1. 0//EN" "http: //www. getahead. ltd. uk/dwr 10. 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:

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

Registering Callback Functions for AJAX-based Asynchronous Invocation 15

How DWR Handles Asynchronous AJAX Call • Calling Java. Script function at the client

How DWR Handles Asynchronous AJAX Call • Calling Java. Script 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

1. How the Callback Function is Registered • Suppose we have a Java method that looks like this: //Server side Java code public class My. Remote. Java. Class{ public String get. Data(int index){…} } • We can use this from Java. Script as follows //Callback function to be called function handle. Get. Data(str) { alert(str); } 17

2. How the Callback Function is Registered • The callback function is passed as

2. How the Callback Function is Registered • The callback function is passed as an additional parameter My. Remote. Java. Script. Class. get. Data(42, handle. Get. Data); • Alternatively you can use the all-in-one-line version Remote. get. Data(42, function(str) { alert(str); }); • Or we can use a call meta-data object that specifies the callback function Remote. get. Data(42, { callback: function(str) { alert(str); } }); • In addition to the callback metadata you can also specify a timeout and an error handler Remote. get. Data(42, { callback: function(str) { alert(str); }, timeout: 5000, error. Handler: function(message) { alert("Oops: " + message); } }); 18

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

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 Java. Script objects to Match Java objects • Suppose you have an

1. Creating Java. Script objects to Match Java objects • Suppose you have an exposed Java method like this: public class Remote { public void set. Person(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 Java. Script objects to Match Java objects • Then you can call

2. Creating Java. Script objects to Match Java objects • Then you can call this from Java. Script like this: var p = { name: "Fred Bloggs", age: 42, appointments: [ new Date(), new Date("1 Jan 2008") ] }; Remote. set. Person(p); • Any fields missing from the Java. Script representation will be left unset in the Java version. 21

Converters 22

Converters 22

Types of Converters • A converter converts data between the client and the server

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 (Http. Servlet. Request, Http. Session, 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.

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. Big. Integer, java. math. Big. Decimal 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 Java. Script date and a java. util. Date, java. sql. Times, or, java. sql. Timestamp 24

1. Bean and Object Converters • The Bean converter converts Plain Old Java •

1. Bean and Object Converters • The Bean converter converts Plain Old Java • Objects (POJOs) into Java. Script 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: <converter="bean" match="your. full. package. Bean. Name"/> • To allow conversion of any class in the given package, or sub package: <converter="bean" match="your. full. package. *"/> 25

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

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 set. Person(Person p) { //. . . } } public class Person { public void set. Name(String name) {. . . } public void set. Age(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. set. Person(p); 26

3. Bean and Object Converters • Restricting Property Conversions Just as you have exclude

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 : <converter="bean" match="com. example. Fred"> <param name="exclude" value="property 1, property 2"/> </convert> • This will ensure that DWR does not call fred. get. Property 1() and fred. get. Property 2. • Alternatively if you prefer to white-list rather than black-list you can do the following: <converter="bean" match="com. example. Fred"> <param name="include" value="property 1, property 2"/> </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: <converter="collection"

Collection Converters • The final two default converters are for maps and collections: <converter="collection" match="java. util. Collection"/> and <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 Java. Script, 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 Java 5 Enums into Java. Script strings and back

1. Enum Converters • Converts Java 5 Enums into Java. Script strings and back again. Not enabled by default. • You can enable the Enum Converter for a single class using the following: <converter="enum" match="your. full. package. Enum. Name"/> • Setting up Java. Script variables public class Remoted { public void set. Status(Status p) { //. . . } } enum Status { PASS, FAIL, } 29

2. Enum Converter • If Remoted was configured as a Creator, and Status is

2. Enum Converter • If Remoted was configured as a Creator, and Status is convertible using the Enum. Converter, then you can call the Java code from Java. Script as follows: Remoted. set. Status("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, DOM 4 J, JDOM

DOM Objects • DWR automatically converts DOM trees from DOM, DOM 4 J, 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

1. Servlet Objects • There are only 2 Java classes that you commonly need to depend on within DWR as a user - Web. Context and Web. Context. Factory. • These classes give you access to the standard HTTP servlet objects: Http. Servlet. Request , Http. Servlet. Response, Http. Session, Servlet. Context, and Servlet. Config • 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

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, Servlet. Context cx, String s) { . . . } } Then you will be able to access it from Javascript just as though the Servlet. Context 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

Creators 34

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

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 Java. Script 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

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 set. Hourly. Pay() method you should put the following into your dwr. xml <create creator="new" javascript="Fred"> <param name="class" value="com. example. Fred"/> <auth method="set. Hourly. Pay" role="admin"/> </create> 36

3. Creators • • • The new creator is declared by default by DWR

3. Creators • • • The new creator is declared by default by DWR as follows: <creator id="new" class="uk. ltd. getahead. dwr. create. New. Creator"/>. 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. to. String(reply) then a new java. util. Date will be constructed using the default constructor, then the to. String() 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

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

Utility Functions 39

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

1. Utility Functions • The util. js contains utility functions to help you update your web pages with Java. Script 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) Øget. Value, get. Values, set. Values Øadd. Rows and remove. All. Rows 40

2. Utility Functions • $(id) is the same as ØDocument. get. Element. By. Id(id)

2. Utility Functions • $(id) is the same as ØDocument. get. Element. By. Id(id) in DOM API • DWRUtil. get. Value(id) get the value(s) out of the HTML elements • DWRUtil. set. Value(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

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. , Java. World. 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

2. Tutorials and Articles about DWR • Ajax for Java developers: Ajax with Direct Web Remoting by Philip Mc. Carthy. Retrieved April 3, 2007 from the World Wide Web: http: //www 128. ibm. com/developerworks/java/library/jajax 3/ Ø 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