SlideShare a Scribd company logo
L2: Web Application Development
Direct Web Remoting (DWR): Ajax made easy…

                          Daniel Bryant
     Department of Computing, FEPS (d.bryant@surrey.ac.uk)
            Tai-Dev Ltd, (daniel.bryant@tai-dev.co.uk)
Today’s roadmap...
•   My life story (in under 3 minutes)…

•   Quick review - so, what is Ajax? (Old school vs new school)

•   DWR
       Introduction
       Looking deeper into DWR (client-side/server-side)
       Implementation
       Demo (and debugging)


•   Quick case study – TriOpsis Ltd

•   DWR is awesome!! But are there any disadvantages?

•   Review
My life story (abridged)…

•   Studying at Surrey for 8 years
       BSc Computing and IT - Placement at DTI (now called BERR, DBIS etc. etc...)
       MSc Internet Computing


•   PhD Student within the Department of Computing
       Argumentation “how humans reason”
       Software Agents “mobile and/or intelligent code”


•   JEE, Web 2.0, J2ME & RDBMS Consultant
       Working freelance for the past 5 years
       Started Tai-Dev Ltd 1 year ago (http://tai-dev.blog.co.uk/)
       J2EE, JEE 5, JSE, J2ME
       Spring, Hibernate, MySQL, GlassFish v2
       HTML, CSS, Javascript
       Prototype, Script.aculo.us, JQuery
       Direct Web Remoting (DWR)…
So, just what is Ajax?

•   “Asynchronous JavaScript and XML”
        “…group of interrelated web development techniques used for creating interactive web
        applications or rich Internet applications.” (Wikipedia, 2008)


•   Building block for “Web 2.0” applications
        Facebook, Google Mail and many more (auto-complete forms)




•   Applications can retrieve data from the server asynchronously in the background
    without interfering with the display and behaviour of the existing page
        No browser plugins (a’la Flash, Flex, SilverLight)


•   The use of JavaScript, XML, or its asynchronous use is not required…
Ajax - the old school way…
        Client


                                              Server




                        http://java.sun.com/developer/technicalArticles/J2EE/AJAX
Old school, not so cool…

• Client-side
      Browser incompatibilities (Microsoft, and then the rest of the world...)
      Long-winded
      Error prone
      Responsible for parsing return data, often XML-based
      Responsible for handling application errors (response codes?)
      Large amount of repeated “boiler plate” code


• Server-side
      Create Servlets (no abstraction, and limited chance to allow design patterns)
      Construct XML document of data
      Responsible for “flattening” Objects and Collections
      Set content-type of return data manually
      Manual error handing (convert Exceptions into response codes?)
Introducing the alternatives…

•   JavaScript Libraries/Frameworks
       dojo, JQuery, Prototype
       Greatly simplify client-side code
       Not so helpful on server-side…


•   JSP Taglibs/JSF Components
       jMaki, Ajax4jsf
       Very easy to utilise
       Limited server-side configuration (majority of focus on existing widgets and services)


•   Proxy-based Frameworks
       Direct Web Remoting (DWR), Rajax
       Best of both worlds
       Language specific on backend (Java)


•   Tip: Always new stuff coming out – check blogs and news sites...
Direct Web Remoting (DWR)
Overview

•   DWR allows easy implementation of Ajax functionality
        Homepage @ http://directwebremoting.org/
        Open source
        JavaScript “client-side”
        Java “server-side”


•   Proxy-based framework
        Client-side code can call Java server-side methods as if they were local
        JavaScript functions.
        Converts or “marshalls” parameters and return variable to/from Java/JavaScript

•   DWR generates the intermediate code (“piping” or boilerplate code)

•   Also provides Utility classes
DWR in pictures




                  Image from http://directwebremoting.org/dwr/overview/dwr
Client-side

•   Core components
        DWR JavaScript engine
        JavaScript “interface” definitions of remote methods
        JavaScript Object Notation (JSON) used instead of XML


•   Call Java methods as if local JavaScript functions
        Albeit with callbacks…


•   Hides browser incompatibilities (via “engine.js”)
        XMLHttpRequest Object
        Maps function calls to URLs


•   Converts or “marshalls” data
        Java ArrayLists into JavaScript arrays
        Java Objects into JavaScript object


•   Simplifies error-handling
        Maps Java Exceptions to JavaScript errors
Server-side

•   Core components
        DWR JAR Library
        Proxy generator
        DWRServlets


•   Easy framework configuration
        XML or Annotations (Java 5+)
        Care needed…


•   Not tied to writing Servlets
        Promotes good OO coding and design patterns


•   Simply expose (existing) Application Services
        Specify order and types of parameter
        Can return any type of Collection or Object
        Can utilise Spring, Struts, JSF…
Implementation in 5 (easy) steps…


1. Copy DWR Library files into project

2. Configure your existing framework to handle DWR requests

3. Create your Data Model (Business Objects) and Application Services

4. Inform DWR of these classes and their required exposure client-side
    1. dwr.xml configuration file
    2. Annotations (Java 5+)


5. Create your client-side functions
Handling http requests (web.xml)….


 …

     <servlet>
         <servlet-name>dwr-invoker</servlet-name>
         <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
         <init-param>
             <param-name>classes</param-name>
             <param-value>
       uk.ac.surrey.wappdev.appservices.FeedbackService,
       uk.ac.surrey.wappdev.model.FeedbackBean
             </param-value>
         </init-param>
     </servlet>

     <servlet-mapping>
         <servlet-name>dwr-invoker</servlet-name>
         <url-pattern>/dwr/*</url-pattern>
     </servlet-mapping>
     …
Create the Model (Business Objects)

package uk.ac.surrey.wappdev.model;

import org.directwebremoting.annotations.DataTransferObject;
import org.directwebremoting.annotations.RemoteProperty;

@DataTransferObject
public class FeedbackBean {

    @RemoteProperty
    private int id;
    @RemoteProperty
    private String feedbackValue;

     public FeedbackBean() {
    }

    public FeedbackBean(int id, String feedbackValue) {
        this.id = id;
        this.feedbackValue = feedbackValue;
    }

    //getter and setter defined here...
…
Create your Application Services…

package uk.ac.surrey.wappdev.appservices;

import ...

@RemoteProxy
public class FeedbackService {

      @RemoteMethod
      public List<FeedbackBean> getFeedbackAvailable() {
          List<FeedbackBean> results = new ArrayList<FeedbackBean>();

          for (int i = 0; i < 5; i++) {
              FeedbackBean fbBean = new FeedbackBean(i, "Feedback Value " + i);
              results.add(fbBean);
          }
          return results;
      }
...
}
Create your client-side functions…
                                                                                            package uk.ac.surrey.wappdev.appservices;

       <script src='dwr/interface/LocService.js'></script>                                  import ...
      <script src='dwr/engine.js'></script>
                                                                                            @RemoteProxy
                                                                                            public class FeedbackService {
      <script>
          function updateFeedback() {                                                           @RemoteMethod
              //alert("updateFeedback()");                                                      public List<FeedbackBean>
                                                                                            getFeedbackAvailable() {
                                                                                                    List<FeedbackBean> results =
                FeedbackService.getFeedbackAvailable({                                                     new ArrayList<FeedbackBean>();
                    callback:function(dataFromServer) {
                        cbUpdateFeedback(dataFromServer);                                           for (int i = 0; i < 5; i++) {
                    },                                                                                  FeedbackBean fbBean =
                                                                                                           new FeedbackBean(i, "Feedback
                    errorHandler:function(errorString, exception) {
                                                                                            Value " + i);
                        alert("Error: " + errorString);                                                 results.add(fbBean);
                    }                                                                               }
                });                                                                                 return results;
            }                                                                                   }
                                                                                            ...
                                                                                            }
            function cbUpdateFeedback(feedbackBeanList) {
                //alert("cbUpdateFeedback()");
                for (var i = 0, l = feedbackBeanList.length; i < l; i++) {

                    var option = document.createElement("option");
                    option.setAttribute("value",feedbackBeanList[i].id);

                    var optText = document.createTextNode(feedbackBeanList[i].feedbackValue);
                    option.appendChild(optText);

                    document.getElementById("feedbackEl").appendChild(option);

                }
            }
</script>
Lights, camera, action...
(oh yes, and debugging)

•   Quick demo of slide material



•   Quick look at debugging
       Client-side – Firefox’s Firebug
       Server-side – Netbeans’ debugger



•   Tip: If you want to be a professional software developer debugging
    efficiently should become as natural as breathing…
       Not emphasized enough in teaching (but this is just my opinion)
       Probably a worthwhile skill for those final year projects as well…
Real world case study... TriOpsis Ltd

 •   Highly innovative start-up company based at the Research Park (STC)
 •   Check out www.triopsis.co.uk for more information
 •   Experts in the emerging field of Visual Business Information
      • Specialising on ‘in the field’ data capture via mobile devices
      • Images and associated metadata reporting relevant to target customer
Real world case study... TriOpsis Ltd




Screenshot of TriOpsis Flagship product – the ‘Asset Manager’ (implemented by yours truly!)
And finally…
There are some disadvantages with DWR…
•   As with any framework that generates (blackbox) “piping”
        Sometimes difficult to know what is happening “in the pipe”


•   Potentially difficult to debug
        Spans across client and server domain
        Can use Netbeans debugger and FireFox’s Firebug


•   Maintaining http session information
        Hybrid of POSTed forms and Ajax


•   Can cause unexpectedly large amounts of http traffic
        Passing of complete object graphs (typically developer error ☺ )


•   Potential security implications
        Exposing incorrect methods etc.
        Easy to pass sensitive data in plaintext (passwords etc.) without knowing
Conclusions

•   We know what Ajax is…

•   We examined old school/new school approaches to implementation

•   We learned that DWR is a “proxy-based” framework
         Providing (JavaScript) client and (Java) server-side Ajax support
         Allows exposure of Java model (BOs) and services
         DWR “handles the details”..


•   We’ve seen how to implement DWR

•   We’ve had a look at an often undervalued skill – debugging

•   Seen real case study using this technology, TriOpsis, which is actively used within Industry

•   And we are always aware of potential disadvantages
         Beware of “black box” implementations…
         Security, session and http traffic
Thanks for your attention…


•   I’m happy to answer questions now or later...



•   If you want to know more about DWR or debugging ask for a lab session
       Sorry, but I can’t answer individual emails...




•   Feedback, comments, constructive criticism...

More Related Content

PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
PPTX
Integration of Backbone.js with Spring 3.1
PDF
DataFX - JavaOne 2013
PDF
Java Web Programming [8/9] : JSF and AJAX
ODP
Java EE and Glassfish
PDF
Lecture 6 Web Sockets
PDF
Java Web Programming [2/9] : Servlet Basic
PPTX
Rest with Java EE 6 , Security , Backbone.js
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
Integration of Backbone.js with Spring 3.1
DataFX - JavaOne 2013
Java Web Programming [8/9] : JSF and AJAX
Java EE and Glassfish
Lecture 6 Web Sockets
Java Web Programming [2/9] : Servlet Basic
Rest with Java EE 6 , Security , Backbone.js

What's hot (20)

PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
PDF
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
PPTX
IndexedDB - Querying and Performance
PDF
Demystifying AJAX Callback Commands in Drupal 8
PDF
Demystifying Drupal AJAX Callback Commands
PDF
Lecture 5 JSTL, custom tags, maven
PPT
Spring Core
PDF
Pragmatic Functional Refactoring with Java 8
PDF
Drupal8Day: Demystifying Drupal 8 Ajax Callback commands
PDF
11-DWR-and-JQuery
PDF
Introduction to Polymer and Firebase - Simon Gauvin
PPS
Jdbc example program with access and MySql
PDF
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
PPTX
Javatwo2012 java frameworkcomparison
PDF
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
DOCX
Advance Java Programs skeleton
PDF
Lecture 3: Servlets - Session Management
PDF
Alfredo-PUMEX
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [3/9] : Servlet Advanced
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
IndexedDB - Querying and Performance
Demystifying AJAX Callback Commands in Drupal 8
Demystifying Drupal AJAX Callback Commands
Lecture 5 JSTL, custom tags, maven
Spring Core
Pragmatic Functional Refactoring with Java 8
Drupal8Day: Demystifying Drupal 8 Ajax Callback commands
11-DWR-and-JQuery
Introduction to Polymer and Firebase - Simon Gauvin
Jdbc example program with access and MySql
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
Javatwo2012 java frameworkcomparison
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Advance Java Programs skeleton
Lecture 3: Servlets - Session Management
Alfredo-PUMEX
Ad

Viewers also liked (20)

PPTX
Continuous Health
PPT
Weather Day 3
PPTX
Maria Mitchell Portfolio
PPSX
Jeopardy Game
PPT
Assignments That Matter F I N A L!
PDF
9782909735221 inquisiteur
KEY
Classroom language
PPT
Corso di Formazione Volontari A 08/09
PPTX
LJCConf 2013 "Chuck Norris Doesn't Need DevOps"
PPT
LJCConf 2013 "Contributing to OpenJDK for the GitHub Generation"
PDF
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
PDF
Cap belgique-discrimination
PDF
Aout 1999
PDF
ContainerSched 2015 "Our journey to world (gifting) domination - how notonthe...
PPT
Quick Business Overview
PPS
Dla Odwaznych
PPTX
Kindle - Why are publishers fighting Amazon over prices?
DOCX
Innovative trends of elearning
PDF
Cucina modello Touch di Oikos
PDF
Disgrafia colombo
Continuous Health
Weather Day 3
Maria Mitchell Portfolio
Jeopardy Game
Assignments That Matter F I N A L!
9782909735221 inquisiteur
Classroom language
Corso di Formazione Volontari A 08/09
LJCConf 2013 "Chuck Norris Doesn't Need DevOps"
LJCConf 2013 "Contributing to OpenJDK for the GitHub Generation"
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
Cap belgique-discrimination
Aout 1999
ContainerSched 2015 "Our journey to world (gifting) domination - how notonthe...
Quick Business Overview
Dla Odwaznych
Kindle - Why are publishers fighting Amazon over prices?
Innovative trends of elearning
Cucina modello Touch di Oikos
Disgrafia colombo
Ad

Similar to L2 Web App Development Guest Lecture At University of Surrey 20/11/09 (20)

PDF
Joe Walker Interactivewebsites Cometand Dwr
PDF
Backbone.js: Run your Application Inside The Browser
PDF
What's New in GWT 2.2
PDF
Not your Grandma's XQuery
PDF
Jsf2 overview
PDF
Ajax tutorial
PPTX
Planbox Backbone MVC
PDF
11-DWR-and-JQuery
PDF
Spark IT 2011 - Java EE 6 Workshop
PPTX
java mini project for college students
PPTX
Soa development using javascript
PDF
Automatically generating-json-from-java-objects-java-objects268
PDF
Backbone.js - Michał Taberski (PRUG 2.0)
PDF
PPTX
Push to the limit - rich and pro-active user interfaces with ADF - V2 (UKOUG,...
PPTX
SCWCD : The servlet model CHAP : 2
PDF
Javascript Application Architecture with Backbone.JS
PDF
XQuery Rocks
PDF
Prototype-1
PDF
Prototype-1
Joe Walker Interactivewebsites Cometand Dwr
Backbone.js: Run your Application Inside The Browser
What's New in GWT 2.2
Not your Grandma's XQuery
Jsf2 overview
Ajax tutorial
Planbox Backbone MVC
11-DWR-and-JQuery
Spark IT 2011 - Java EE 6 Workshop
java mini project for college students
Soa development using javascript
Automatically generating-json-from-java-objects-java-objects268
Backbone.js - Michał Taberski (PRUG 2.0)
Push to the limit - rich and pro-active user interfaces with ADF - V2 (UKOUG,...
SCWCD : The servlet model CHAP : 2
Javascript Application Architecture with Backbone.JS
XQuery Rocks
Prototype-1
Prototype-1

More from Daniel Bryant (20)

PDF
ITKonekt 2023: The Busy Platform Engineers Guide to API Gateways
PDF
CraftConf 2023 "Microservice Testing Techniques: Mocks vs Service Virtualizat...
PDF
PlatformCon 23: "The Busy Platform Engineers Guide to API Gateways"
PDF
Java Meetup 23: 'Debugging Microservices "Remocally" in Kubernetes with Telep...
PPTX
DevRelCon 2022: "Is Product Led Growth (PLG) the “DevOps” of the DevRel World"
PDF
Fall 22: "From Kubernetes to PaaS to... err, what's next"
PDF
Building Microservice Systems Without Cooking Your Laptop: Going “Remocal” wi...
PDF
KubeCrash 22: Debugging Microservices "Remocally" in Kubernetes with Telepres...
PDF
JAX London 22: Debugging Microservices "Remocally" in Kubernetes with Telepre...
PDF
CloudBuilders 2022: "The Past, Present, and Future of Cloud Native API Gateways"
PDF
KubeCon EU 2022: From Kubernetes to PaaS to Err What's Next
PDF
Devoxx UK 22: Debugging Java Microservices "Remocally" in Kubernetes with Tel...
PDF
DevXDay KubeCon NA 2021: "From Kubernetes to PaaS to Developer Control Planes"
PDF
JAX London 2021: Jumpstart Your Cloud Native Development: An Overview of Prac...
PDF
Container Days: Easy Debugging of Microservices Running on Kubernetes with Te...
PDF
Canadian CNCF: "Emissary-ingress 101: An introduction to the CNCF incubation-...
PDF
MJC 2021: "Debugging Java Microservices Running on Kubernetes with Telepresence"
PDF
LJC 4/21"Easy Debugging of Java Microservices Running on Kubernetes with Tele...
PDF
GOTOpia 2/2021 "Cloud Native Development Without the Toil: An Overview of Pra...
PPTX
HashiCorp Webinar: "Getting started with Ambassador and Consul on Kubernetes ...
ITKonekt 2023: The Busy Platform Engineers Guide to API Gateways
CraftConf 2023 "Microservice Testing Techniques: Mocks vs Service Virtualizat...
PlatformCon 23: "The Busy Platform Engineers Guide to API Gateways"
Java Meetup 23: 'Debugging Microservices "Remocally" in Kubernetes with Telep...
DevRelCon 2022: "Is Product Led Growth (PLG) the “DevOps” of the DevRel World"
Fall 22: "From Kubernetes to PaaS to... err, what's next"
Building Microservice Systems Without Cooking Your Laptop: Going “Remocal” wi...
KubeCrash 22: Debugging Microservices "Remocally" in Kubernetes with Telepres...
JAX London 22: Debugging Microservices "Remocally" in Kubernetes with Telepre...
CloudBuilders 2022: "The Past, Present, and Future of Cloud Native API Gateways"
KubeCon EU 2022: From Kubernetes to PaaS to Err What's Next
Devoxx UK 22: Debugging Java Microservices "Remocally" in Kubernetes with Tel...
DevXDay KubeCon NA 2021: "From Kubernetes to PaaS to Developer Control Planes"
JAX London 2021: Jumpstart Your Cloud Native Development: An Overview of Prac...
Container Days: Easy Debugging of Microservices Running on Kubernetes with Te...
Canadian CNCF: "Emissary-ingress 101: An introduction to the CNCF incubation-...
MJC 2021: "Debugging Java Microservices Running on Kubernetes with Telepresence"
LJC 4/21"Easy Debugging of Java Microservices Running on Kubernetes with Tele...
GOTOpia 2/2021 "Cloud Native Development Without the Toil: An Overview of Pra...
HashiCorp Webinar: "Getting started with Ambassador and Consul on Kubernetes ...

L2 Web App Development Guest Lecture At University of Surrey 20/11/09

  • 1. L2: Web Application Development Direct Web Remoting (DWR): Ajax made easy… Daniel Bryant Department of Computing, FEPS (d.bryant@surrey.ac.uk) Tai-Dev Ltd, (daniel.bryant@tai-dev.co.uk)
  • 2. Today’s roadmap... • My life story (in under 3 minutes)… • Quick review - so, what is Ajax? (Old school vs new school) • DWR Introduction Looking deeper into DWR (client-side/server-side) Implementation Demo (and debugging) • Quick case study – TriOpsis Ltd • DWR is awesome!! But are there any disadvantages? • Review
  • 3. My life story (abridged)… • Studying at Surrey for 8 years BSc Computing and IT - Placement at DTI (now called BERR, DBIS etc. etc...) MSc Internet Computing • PhD Student within the Department of Computing Argumentation “how humans reason” Software Agents “mobile and/or intelligent code” • JEE, Web 2.0, J2ME & RDBMS Consultant Working freelance for the past 5 years Started Tai-Dev Ltd 1 year ago (http://tai-dev.blog.co.uk/) J2EE, JEE 5, JSE, J2ME Spring, Hibernate, MySQL, GlassFish v2 HTML, CSS, Javascript Prototype, Script.aculo.us, JQuery Direct Web Remoting (DWR)…
  • 4. So, just what is Ajax? • “Asynchronous JavaScript and XML” “…group of interrelated web development techniques used for creating interactive web applications or rich Internet applications.” (Wikipedia, 2008) • Building block for “Web 2.0” applications Facebook, Google Mail and many more (auto-complete forms) • Applications can retrieve data from the server asynchronously in the background without interfering with the display and behaviour of the existing page No browser plugins (a’la Flash, Flex, SilverLight) • The use of JavaScript, XML, or its asynchronous use is not required…
  • 5. Ajax - the old school way… Client Server http://java.sun.com/developer/technicalArticles/J2EE/AJAX
  • 6. Old school, not so cool… • Client-side Browser incompatibilities (Microsoft, and then the rest of the world...) Long-winded Error prone Responsible for parsing return data, often XML-based Responsible for handling application errors (response codes?) Large amount of repeated “boiler plate” code • Server-side Create Servlets (no abstraction, and limited chance to allow design patterns) Construct XML document of data Responsible for “flattening” Objects and Collections Set content-type of return data manually Manual error handing (convert Exceptions into response codes?)
  • 7. Introducing the alternatives… • JavaScript Libraries/Frameworks dojo, JQuery, Prototype Greatly simplify client-side code Not so helpful on server-side… • JSP Taglibs/JSF Components jMaki, Ajax4jsf Very easy to utilise Limited server-side configuration (majority of focus on existing widgets and services) • Proxy-based Frameworks Direct Web Remoting (DWR), Rajax Best of both worlds Language specific on backend (Java) • Tip: Always new stuff coming out – check blogs and news sites...
  • 8. Direct Web Remoting (DWR) Overview • DWR allows easy implementation of Ajax functionality Homepage @ http://directwebremoting.org/ Open source JavaScript “client-side” Java “server-side” • Proxy-based framework Client-side code can call Java server-side methods as if they were local JavaScript functions. Converts or “marshalls” parameters and return variable to/from Java/JavaScript • DWR generates the intermediate code (“piping” or boilerplate code) • Also provides Utility classes
  • 9. DWR in pictures Image from http://directwebremoting.org/dwr/overview/dwr
  • 10. Client-side • Core components DWR JavaScript engine JavaScript “interface” definitions of remote methods JavaScript Object Notation (JSON) used instead of XML • Call Java methods as if local JavaScript functions Albeit with callbacks… • Hides browser incompatibilities (via “engine.js”) XMLHttpRequest Object Maps function calls to URLs • Converts or “marshalls” data Java ArrayLists into JavaScript arrays Java Objects into JavaScript object • Simplifies error-handling Maps Java Exceptions to JavaScript errors
  • 11. Server-side • Core components DWR JAR Library Proxy generator DWRServlets • Easy framework configuration XML or Annotations (Java 5+) Care needed… • Not tied to writing Servlets Promotes good OO coding and design patterns • Simply expose (existing) Application Services Specify order and types of parameter Can return any type of Collection or Object Can utilise Spring, Struts, JSF…
  • 12. Implementation in 5 (easy) steps… 1. Copy DWR Library files into project 2. Configure your existing framework to handle DWR requests 3. Create your Data Model (Business Objects) and Application Services 4. Inform DWR of these classes and their required exposure client-side 1. dwr.xml configuration file 2. Annotations (Java 5+) 5. Create your client-side functions
  • 13. Handling http requests (web.xml)…. … <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>classes</param-name> <param-value> uk.ac.surrey.wappdev.appservices.FeedbackService, uk.ac.surrey.wappdev.model.FeedbackBean </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> …
  • 14. Create the Model (Business Objects) package uk.ac.surrey.wappdev.model; import org.directwebremoting.annotations.DataTransferObject; import org.directwebremoting.annotations.RemoteProperty; @DataTransferObject public class FeedbackBean { @RemoteProperty private int id; @RemoteProperty private String feedbackValue; public FeedbackBean() { } public FeedbackBean(int id, String feedbackValue) { this.id = id; this.feedbackValue = feedbackValue; } //getter and setter defined here... …
  • 15. Create your Application Services… package uk.ac.surrey.wappdev.appservices; import ... @RemoteProxy public class FeedbackService { @RemoteMethod public List<FeedbackBean> getFeedbackAvailable() { List<FeedbackBean> results = new ArrayList<FeedbackBean>(); for (int i = 0; i < 5; i++) { FeedbackBean fbBean = new FeedbackBean(i, "Feedback Value " + i); results.add(fbBean); } return results; } ... }
  • 16. Create your client-side functions… package uk.ac.surrey.wappdev.appservices; <script src='dwr/interface/LocService.js'></script> import ... <script src='dwr/engine.js'></script> @RemoteProxy public class FeedbackService { <script> function updateFeedback() { @RemoteMethod //alert("updateFeedback()"); public List<FeedbackBean> getFeedbackAvailable() { List<FeedbackBean> results = FeedbackService.getFeedbackAvailable({ new ArrayList<FeedbackBean>(); callback:function(dataFromServer) { cbUpdateFeedback(dataFromServer); for (int i = 0; i < 5; i++) { }, FeedbackBean fbBean = new FeedbackBean(i, "Feedback errorHandler:function(errorString, exception) { Value " + i); alert("Error: " + errorString); results.add(fbBean); } } }); return results; } } ... } function cbUpdateFeedback(feedbackBeanList) { //alert("cbUpdateFeedback()"); for (var i = 0, l = feedbackBeanList.length; i < l; i++) { var option = document.createElement("option"); option.setAttribute("value",feedbackBeanList[i].id); var optText = document.createTextNode(feedbackBeanList[i].feedbackValue); option.appendChild(optText); document.getElementById("feedbackEl").appendChild(option); } } </script>
  • 17. Lights, camera, action... (oh yes, and debugging) • Quick demo of slide material • Quick look at debugging Client-side – Firefox’s Firebug Server-side – Netbeans’ debugger • Tip: If you want to be a professional software developer debugging efficiently should become as natural as breathing… Not emphasized enough in teaching (but this is just my opinion) Probably a worthwhile skill for those final year projects as well…
  • 18. Real world case study... TriOpsis Ltd • Highly innovative start-up company based at the Research Park (STC) • Check out www.triopsis.co.uk for more information • Experts in the emerging field of Visual Business Information • Specialising on ‘in the field’ data capture via mobile devices • Images and associated metadata reporting relevant to target customer
  • 19. Real world case study... TriOpsis Ltd Screenshot of TriOpsis Flagship product – the ‘Asset Manager’ (implemented by yours truly!)
  • 20. And finally… There are some disadvantages with DWR… • As with any framework that generates (blackbox) “piping” Sometimes difficult to know what is happening “in the pipe” • Potentially difficult to debug Spans across client and server domain Can use Netbeans debugger and FireFox’s Firebug • Maintaining http session information Hybrid of POSTed forms and Ajax • Can cause unexpectedly large amounts of http traffic Passing of complete object graphs (typically developer error ☺ ) • Potential security implications Exposing incorrect methods etc. Easy to pass sensitive data in plaintext (passwords etc.) without knowing
  • 21. Conclusions • We know what Ajax is… • We examined old school/new school approaches to implementation • We learned that DWR is a “proxy-based” framework Providing (JavaScript) client and (Java) server-side Ajax support Allows exposure of Java model (BOs) and services DWR “handles the details”.. • We’ve seen how to implement DWR • We’ve had a look at an often undervalued skill – debugging • Seen real case study using this technology, TriOpsis, which is actively used within Industry • And we are always aware of potential disadvantages Beware of “black box” implementations… Security, session and http traffic
  • 22. Thanks for your attention… • I’m happy to answer questions now or later... • If you want to know more about DWR or debugging ask for a lab session Sorry, but I can’t answer individual emails... • Feedback, comments, constructive criticism...