Your SlideShare is downloading. ×
0
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
11-DWR-and-JQuery
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

11-DWR-and-JQuery

785

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
785
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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
  • 18. Converters 18
  • 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
  • 32. Utility Functions 32
  • 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
  • 35. jQuery
  • 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(); });

×