SlideShare a Scribd company logo
11- DWR (2) and JQuery



       A. Venturini
What is Ajax?

   Two components:
       Client Side (e.g. JavaScript)
            determine when to contact
             server
            contact it
            display results on page


       Server side (e.g. Java, PHP)
            like normal servlet but return specifically
             what is required
                maybe just OK or Fail
                maybe XML or HTML
                                                           2
What is Ajax?




     Diagram from:
      http://www.codeproject.com/KB/showcase/FarPointAJAX.aspx
                                                                 3
07/05/2009                                                           3
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”




                                                   4
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




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




                                                            6
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

                                                           7
Steps for Building DWR-based
AJAX Application

sample application on the lab
site:
modalDialogPortlet-portlet


                                8
GOAL: Make available remotely this class
defined server side
public class Counter {

    public Counter() {
    }

  public String increaseCounter(int num) {
     HttpSession session = WebContextFactory.get().getSession(true);
     Integer counter=(Integer) session.getAttribute("COUNTER");
     if(counter ==null) {
        counter = new Integer(0);
     }
     int iValue=counter.intValue();
     iValue=iValue+num;
     counter=new Integer(iValue);
    session.setAttribute("COUNTER",counter);
     return counter.toString();
  }
public String getCounter() {
     HttpSession session = WebContextFactory.get().getSession(true);
     Integer counter=(Integer) session.getAttribute("COUNTER");
     if(counter ==null) {
        counter = new Integer(0);
     }
     int iValue=counter.intValue();
     return counter.toString();
  }

}
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

                                                       10
Step #2 Edit web.xml in the WEB-
INF 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>
                                                      11
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>
<dwr>
 <allow>
<create creator="new" javascript="Counter">
   <param name="class"
  value="it.unibz.awp.dwr.services.Counter"/>
  </create>
 </allow>
</dwr>
                                                           12
Test and Deploy the Portlet




                              13
Javascript class automatically created
by DWR
<script type="text/javascript"
  src="/modalDialogPortlet-
  portlet/dwr/interface/Counter.js"></script>


It creates dynamically a javascript class as a proxy
   of the methods exposed server side:
1) Counter.increaseCounter(value, yourCallback)
2) Counter.getCounter(anotherCallback)
the HTML is:



Counter is: <span id="counter" class="reply">""</span>
 <br/>
 increase the counter by: <input class="itext" size="10"
   value="1" id="p00" title="Will be converted to: int" type="text">
 <input class="ibutton"
  onclick='Counter.increaseCounter(objectEval($("p00").value),
  getCounterCallback);' value="Execute" type="button">
<br/>
When the button is pressed:

1) the javascript calls the
  Counter.increaseCounter(objectEval($("p00").val
  ue), getCounterCallback)
2) the increaseCounter is called on the server side
3) then getCounterCallback is called
And the callback is:

function getCounterCallback(data) {
    Counter.getCounter(function(data)
    {dwr.util.setValue("counter", data,
          { escapeHtml:false }
          );
    });
}


When the callback is called it gets the updated
 version of the counter (another Ajax call) and
 update the edit box
Converters




             18
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

                                                                  19
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




                                                                                   20
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.*"/>


                                                              21
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 };
                                                                   22
 Remoted.setPerson(p);
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.

                                                                    23
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,
   }
                                                                    24
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.




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




                                                    26
Creators




           27
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.                        28
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>
                                                               29
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).


                                                                             30
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

                                                      31
Utility Functions




                    32
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




                                                         33
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




                                                        34
jQuery
What is jQuery?
   A framework for Client Side JavaScript.
   Frameworks provide useful alternatives for
    common programming tasks, creating
    functionality which may not be available or
    cumbersome to use within a language.
   An open source project, maintained by a group of
    developers, with a very active support base and
    thorough, well written documentation.
   Adopted by Liferay as javascript framework
What jQuery is not…

   A substitute for knowing JavaScript
       jQuery is extraordinarily useful, but you should
        still know how JavaScript works and how to
        use it correctly. This means more than
        Googling a tutorial and calling yourself an
        expert.
   A solve all
       There is still plenty of functionality built into
        JavaScript that should be utilized! Don‟t turn
        every project into a quest to „jQuery-ize‟ the
        problem, use jQuery where it makes sense.
        Create solutions in environments where they
        belong.
What is available with jQuery?

 Cross browser       JavaScript
  support and          animation
  detection           Hundreds of
 AJAX functions       plugins for pre-
 CSS functions        built user
                       interfaces,
 DOM manipulation
                       advanced
 DOM transversal      animations, form
 Attribute            validation, etc
  manipulation        Expandable
 Event detection      functionality using
  and handling         custom plugins
                      Small foot print
jQuery Syntax

                         $.func(…);
                                or
   $(selector).func1(…).func2(…).funcN(…);

            jQuery Object, can be used instead of jQuery (in liferay
       $
            should be used always JQuery)
 selector
            Selector syntax, many different selectors allowed
    func
            Chainable, most functions return a jQuery object
     (…)
            Function parameters
The jQuery/$ Object

   Represented by both $ and jQuery
       To use jQuery only, use jQuery.noConflict(),
        for other frameworks that use $
   By default, represents the jQuery object. When
    combined with a selector, can represent multiple
    DOM Elements, see next slide.
   Used with all jQuery functions.
jQuery Selectors
   $( html )                      $( expr, context )
    Create DOM elements on-         This function accepts a
    the-fly from the provided       string containing a CSS or
    String of raw HTML.             basic XPath selector which
                                    is then used to match a set
                                    of elements. Default
   $( elems )                      context is document. Used
    Wrap jQuery functionality       most often for DOM
    around single or multiple       transversal.
    DOM Elements.
                                   Selectors will return a
   $( fn )                         jQuery object, which can
                                    contain one or more
    A shorthand for                 elements, or contain no
    $(document).ready(),            elements at all.
    allowing you to bind a
    function to be executed
    when the DOM document
    has finished loading.
jQuery Selector Examples
   $( html )
        $(„<p><a href=“index.html”>Click here!</a></p>‟)


   $ ( elems )
        $(document), $(window), $(this)


        $(document.getElementsByTagName(“p”))


   $ ( fn )
        $(function() { alert(“Hello, World!”) });


   $ ( expr, context )
        $(“p”), $(“form”), $(“input”)
jQuery Functions

   Attached to the jQuery object or chained off of a
    selector statement.
   Most functions return the jQuery object they
    were originally passed, so you can perform many
    actions in a single line.
   The same function can perform an entirely
    different action based on the number and type of
    parameters.
jQuery Usage Example


  $(“li:odd”).prepend(„<span>Changed</span>‟).css({background:“red”});

 <ul>                  <ul>                       <ul>
   <li>                  <li>                       <li style=“background:red;”>
     First item            <span>Changed</span>       <span>Changed</span>
   </li>                   First item                 First item
   <li>                  </li>                      </li>
     Second item         <li>                       <li>
   </li>                   Second item                Second item
   <li>                  </li>                      </li>
     Third item          <li>                       <li style=“background:red;”>
   </li>                   <span>Changed</span>       <span>Changed</span>
 </ul>                     Third item                 Third item
                         </li>                      </li>
                       </ul>                      </ul>
jQuery Usage Example

    $(“div:hidden”).find(“.foo”).empty().text(“Changed”).end().show();

 <div>                        <div>                        <div>
   <span class=“foo”>           <span class=“foo”>           <span class=“foo”>
     Some text                    Some text                    Some text
   </span>                      </span>                      </span>
 </div>                       </div>                       </div>
 <div style=“display:none”>   <div style=“display:none”>   <div style=“display:none”>
   <span>                       <span>                       <span>
     More text                    More text                    More text
   </span>                      </span>                      </span>
   <span class=“foo”>           <span class=“foo”>           <span class=“foo”>
     Goodbye cruel world.         Goodbye cruel world.       </span>
   </span>                      </span>                    </div>
 </div>                       </div>



 <div>                        <div>                        <div>
   <span class=“foo”>           <span class=“foo”>           <span class=“foo”>
     Some text                    Some text                    Some text
   </span>                      </span>                      </span>
 </div>                       </div>                       </div>
 <div style=“display:none”>   <div style=“display:none”>   <div style=“display:block”>
   <span>                       <span>                       <span>
     More text                    More text                    More text
   </span>                      </span>                      </span>
   <span class=“foo”>           <span class=“foo”>           <span class=“foo”>
     Changed                      Changed                      Changed
   </span>                      </span>                      </span>
 </div>                       </div>                       </div>
Example JQuery (from the
modalDialogPortlet-portlet)
The HTML
<script type="text/javascript"
  src="/html/js/jquery/ui.tabs.js"></script>


<div id="tabsExamples">
     <ul>
       <li><a href="#tabexample1"><span>TAB1</span></a></li>
       <li><a href="#tabexample2"><span>TAB2</span></a></li>
     </ul>
  </div>
  <div id="tabexample1">hello, I am TAB 1</div>
  <div id="tabexample2">And I am TAB 2</div>
The Javascript


jQuery(document).ready(function(){
    jQuery("#tabsExamples > ul").tabs();
  });

More Related Content

PDF
Java Web Programming [2/9] : Servlet Basic
PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
PPT
Data Access with JDBC
PDF
Java Web Programming [8/9] : JSF and AJAX
PPTX
Rest with Java EE 6 , Security , Backbone.js
PPTX
Java Servlet
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Spring 3: What's New
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Data Access with JDBC
Java Web Programming [8/9] : JSF and AJAX
Rest with Java EE 6 , Security , Backbone.js
Java Servlet
Java Web Programming [3/9] : Servlet Advanced
Spring 3: What's New

What's hot (19)

PPTX
JSP- JAVA SERVER PAGES
PPT
Java servlet life cycle - methods ppt
PPTX
Database connect
PPT
Servlet ppt by vikas jagtap
PPTX
Integration of Backbone.js with Spring 3.1
PDF
Java EE 與 雲端運算的展望
PPS
Jdbc example program with access and MySql
PPTX
Advance Java Programming (CM5I)5.Interacting with-database
PPT
Introducing dwr (direct web remoting)
PPS
Jdbc api
PDF
Java Web Programming [6/9] : MVC
PDF
Lecture 3: Servlets - Session Management
ODP
Interoperable Web Services with JAX-WS
PPTX
JSP - Java Server Page
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PDF
Jasigsakai12 columbia-customizes-cas
ODP
Interoperable Web Services with JAX-WS and WSIT
PDF
Introduction to JDBC and database access in web applications
PPT
JAVA Servlets
JSP- JAVA SERVER PAGES
Java servlet life cycle - methods ppt
Database connect
Servlet ppt by vikas jagtap
Integration of Backbone.js with Spring 3.1
Java EE 與 雲端運算的展望
Jdbc example program with access and MySql
Advance Java Programming (CM5I)5.Interacting with-database
Introducing dwr (direct web remoting)
Jdbc api
Java Web Programming [6/9] : MVC
Lecture 3: Servlets - Session Management
Interoperable Web Services with JAX-WS
JSP - Java Server Page
JAVA EE DEVELOPMENT (JSP and Servlets)
Jasigsakai12 columbia-customizes-cas
Interoperable Web Services with JAX-WS and WSIT
Introduction to JDBC and database access in web applications
JAVA Servlets
Ad

Viewers also liked (8)

PPTX
PPT
PDF
Jeni J2 Me Bab11 Topik Topik Tambahan
PDF
rubyonrails
PDF
Tutorial
PDF
instaling
PDF
How%20to%20install%20PHP%20on%20Linux%20_%20laffers
PDF
Perl%20SYLLABUS%20PB
Jeni J2 Me Bab11 Topik Topik Tambahan
rubyonrails
Tutorial
instaling
How%20to%20install%20PHP%20on%20Linux%20_%20laffers
Perl%20SYLLABUS%20PB
Ad

Similar to 11-DWR-and-JQuery (20)

PDF
PDF
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
PPT
Direct Web Remoting : DWR
PPT
Ajax with DWR
PDF
Joe Walker Interactivewebsites Cometand Dwr
PPTX
Dwr explanation
PPT
PDF
What's new in DWR version 3
PDF
GWT-Basics
PDF
GWT-Basics
PPTX
Gwt session
PPTX
Gwt session
PPT
J2EE - Practical Overview
PDF
Automatically generating-json-from-java-objects-java-objects268
PDF
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
PPT
DWR, Hibernate and Dojo.E - A Tutorial
PPT
J2 Ee Overview
PPTX
Introduction to AJAX and DWR
PPT
Ppt for Online music store
PPTX
Planbox Backbone MVC
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
Direct Web Remoting : DWR
Ajax with DWR
Joe Walker Interactivewebsites Cometand Dwr
Dwr explanation
What's new in DWR version 3
GWT-Basics
GWT-Basics
Gwt session
Gwt session
J2EE - Practical Overview
Automatically generating-json-from-java-objects-java-objects268
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
DWR, Hibernate and Dojo.E - A Tutorial
J2 Ee Overview
Introduction to AJAX and DWR
Ppt for Online music store
Planbox Backbone MVC

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
PDF
&lt;img src="../i/r_14.png" />
PDF
&lt;img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
&lt;img src="../i/r_14.png" />
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Big Data Technologies - Introduction.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Cloud computing and distributed systems.
PDF
KodekX | Application Modernization Development
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Empathic Computing: Creating Shared Understanding
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Big Data Technologies - Introduction.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Spectral efficient network and resource selection model in 5G networks
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Cloud computing and distributed systems.
KodekX | Application Modernization Development
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Dropbox Q2 2025 Financial Results & Investor Presentation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

11-DWR-and-JQuery

  • 1. 11- DWR (2) and JQuery A. Venturini
  • 2. What is Ajax?  Two components:  Client Side (e.g. JavaScript)  determine when to contact server  contact it  display results on page  Server side (e.g. Java, PHP)  like normal servlet but return specifically what is required  maybe just OK or Fail  maybe XML or HTML 2
  • 3. What is Ajax?  Diagram from: http://www.codeproject.com/KB/showcase/FarPointAJAX.aspx 3 07/05/2009 3
  • 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” 4
  • 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 5
  • 6. 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. 6
  • 7. 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 7
  • 8. Steps for Building DWR-based AJAX Application sample application on the lab site: modalDialogPortlet-portlet 8
  • 9. GOAL: Make available remotely this class defined server side public class Counter { public Counter() { } public String increaseCounter(int num) { HttpSession session = WebContextFactory.get().getSession(true); Integer counter=(Integer) session.getAttribute("COUNTER"); if(counter ==null) { counter = new Integer(0); } int iValue=counter.intValue(); iValue=iValue+num; counter=new Integer(iValue); session.setAttribute("COUNTER",counter); return counter.toString(); } public String getCounter() { HttpSession session = WebContextFactory.get().getSession(true); Integer counter=(Integer) session.getAttribute("COUNTER"); if(counter ==null) { counter = new Integer(0); } int iValue=counter.intValue(); return counter.toString(); } }
  • 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 10
  • 11. Step #2 Edit web.xml in the WEB- INF 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> 11
  • 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> <dwr> <allow> <create creator="new" javascript="Counter"> <param name="class" value="it.unibz.awp.dwr.services.Counter"/> </create> </allow> </dwr> 12
  • 13. Test and Deploy the Portlet 13
  • 14. Javascript class automatically created by DWR <script type="text/javascript" src="/modalDialogPortlet- portlet/dwr/interface/Counter.js"></script> It creates dynamically a javascript class as a proxy of the methods exposed server side: 1) Counter.increaseCounter(value, yourCallback) 2) Counter.getCounter(anotherCallback)
  • 15. the HTML is: Counter is: <span id="counter" class="reply">""</span> <br/> increase the counter by: <input class="itext" size="10" value="1" id="p00" title="Will be converted to: int" type="text"> <input class="ibutton" onclick='Counter.increaseCounter(objectEval($("p00").value), getCounterCallback);' value="Execute" type="button"> <br/>
  • 16. When the button is pressed: 1) the javascript calls the Counter.increaseCounter(objectEval($("p00").val ue), getCounterCallback) 2) the increaseCounter is called on the server side 3) then getCounterCallback is called
  • 17. And the callback is: function getCounterCallback(data) { Counter.getCounter(function(data) {dwr.util.setValue("counter", data, { escapeHtml:false } ); }); } When the callback is called it gets the updated version of the counter (another Ajax call) and update the edit box
  • 19. 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 19
  • 20. 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 20
  • 21. 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.*"/> 21
  • 22. 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 }; 22 Remoted.setPerson(p);
  • 23. 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. 23
  • 24. 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, } 24
  • 25. 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. 25
  • 26. 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. 26
  • 27. Creators 27
  • 28. 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. 28
  • 29. 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> 29
  • 30. 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). 30
  • 31. 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 31
  • 33. 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 33
  • 34. 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 34
  • 36. What is jQuery?  A framework for Client Side JavaScript.  Frameworks provide useful alternatives for common programming tasks, creating functionality which may not be available or cumbersome to use within a language.  An open source project, maintained by a group of developers, with a very active support base and thorough, well written documentation.  Adopted by Liferay as javascript framework
  • 37. What jQuery is not…  A substitute for knowing JavaScript  jQuery is extraordinarily useful, but you should still know how JavaScript works and how to use it correctly. This means more than Googling a tutorial and calling yourself an expert.  A solve all  There is still plenty of functionality built into JavaScript that should be utilized! Don‟t turn every project into a quest to „jQuery-ize‟ the problem, use jQuery where it makes sense. Create solutions in environments where they belong.
  • 38. What is available with jQuery?  Cross browser  JavaScript support and animation detection  Hundreds of  AJAX functions plugins for pre-  CSS functions built user interfaces,  DOM manipulation advanced  DOM transversal animations, form  Attribute validation, etc manipulation  Expandable  Event detection functionality using and handling custom plugins  Small foot print
  • 39. jQuery Syntax $.func(…); or $(selector).func1(…).func2(…).funcN(…); jQuery Object, can be used instead of jQuery (in liferay $ should be used always JQuery) selector Selector syntax, many different selectors allowed func Chainable, most functions return a jQuery object (…) Function parameters
  • 40. The jQuery/$ Object  Represented by both $ and jQuery  To use jQuery only, use jQuery.noConflict(), for other frameworks that use $  By default, represents the jQuery object. When combined with a selector, can represent multiple DOM Elements, see next slide.  Used with all jQuery functions.
  • 41. jQuery Selectors  $( html )  $( expr, context ) Create DOM elements on- This function accepts a the-fly from the provided string containing a CSS or String of raw HTML. basic XPath selector which is then used to match a set of elements. Default  $( elems ) context is document. Used Wrap jQuery functionality most often for DOM around single or multiple transversal. DOM Elements.  Selectors will return a  $( fn ) jQuery object, which can contain one or more A shorthand for elements, or contain no $(document).ready(), elements at all. allowing you to bind a function to be executed when the DOM document has finished loading.
  • 42. jQuery Selector Examples  $( html )  $(„<p><a href=“index.html”>Click here!</a></p>‟)  $ ( elems )  $(document), $(window), $(this)  $(document.getElementsByTagName(“p”))  $ ( fn )  $(function() { alert(“Hello, World!”) });  $ ( expr, context )  $(“p”), $(“form”), $(“input”)
  • 43. jQuery Functions  Attached to the jQuery object or chained off of a selector statement.  Most functions return the jQuery object they were originally passed, so you can perform many actions in a single line.  The same function can perform an entirely different action based on the number and type of parameters.
  • 44. jQuery Usage Example $(“li:odd”).prepend(„<span>Changed</span>‟).css({background:“red”}); <ul> <ul> <ul> <li> <li> <li style=“background:red;”> First item <span>Changed</span> <span>Changed</span> </li> First item First item <li> </li> </li> Second item <li> <li> </li> Second item Second item <li> </li> </li> Third item <li> <li style=“background:red;”> </li> <span>Changed</span> <span>Changed</span> </ul> Third item Third item </li> </li> </ul> </ul>
  • 45. jQuery Usage Example $(“div:hidden”).find(“.foo”).empty().text(“Changed”).end().show(); <div> <div> <div> <span class=“foo”> <span class=“foo”> <span class=“foo”> Some text Some text Some text </span> </span> </span> </div> </div> </div> <div style=“display:none”> <div style=“display:none”> <div style=“display:none”> <span> <span> <span> More text More text More text </span> </span> </span> <span class=“foo”> <span class=“foo”> <span class=“foo”> Goodbye cruel world. Goodbye cruel world. </span> </span> </span> </div> </div> </div> <div> <div> <div> <span class=“foo”> <span class=“foo”> <span class=“foo”> Some text Some text Some text </span> </span> </span> </div> </div> </div> <div style=“display:none”> <div style=“display:none”> <div style=“display:block”> <span> <span> <span> More text More text More text </span> </span> </span> <span class=“foo”> <span class=“foo”> <span class=“foo”> Changed Changed Changed </span> </span> </span> </div> </div> </div>
  • 46. Example JQuery (from the modalDialogPortlet-portlet)
  • 47. The HTML <script type="text/javascript" src="/html/js/jquery/ui.tabs.js"></script> <div id="tabsExamples"> <ul> <li><a href="#tabexample1"><span>TAB1</span></a></li> <li><a href="#tabexample2"><span>TAB2</span></a></li> </ul> </div> <div id="tabexample1">hello, I am TAB 1</div> <div id="tabexample2">And I am TAB 2</div>
  • 48. The Javascript jQuery(document).ready(function(){ jQuery("#tabsExamples > ul").tabs(); });