DWR, Hibernate and Dojo.E - A Tutorial

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    1 Favorite

    DWR, Hibernate and Dojo.E - A Tutorial - Presentation Transcript

    1. Direct Web Remoting, Hibernate and Dojo.E “ Easy Ajax for Java” Joel Barciauskas October 3, 2008
    2. What is DWR?
      • “ Easy Ajax for Java” implies two parts
        • Server – Java servlet
        • Client – JavaScript auto-generated by the Java servlet
      • Enables JSON to JavaBean serialization
      • Exposes selected methods and JavaBean properties on the server as client-side JavaScript methods and objects
      • Reverse Ajax – IMB-like functionality
    3. Why use DWR? Why not?
      • Pros
        • Avoid replication of effort defining model objects on both server and client
        • No XHR boilerplate required
        • No serialization boilerplate
        • JSON is fastest format to serialize/deserialize in the browser
      • Cons
        • Less control over network requests
          • E.g., harder to bundle requests
        • Not RESTful, all requests processed through POST data rather than URLs
          • Best for single-page applications
    4. Let’s see it
      • Application: Simple database create and read
      • Using: JavaScript, DWR 2.0, Hibernate 3.0, Derby
      • Shell: http://source.nexaweb.com/svn/repos/trunk/tutorials/ajax/DWRExample/
    5. Create your domain class (JavaBean)
      • src/events/Event.java
      • package events;
      • import java.util.Date;
      • public class Event {
      • private Long id;
      • private String title;
      • private Date date;
      • public Event() {}
      • public Long getId() { return id; }
      • private void setId(Long id) { this.id = id; }
      • public Date getDate() { return date; }
      • public void setDate(Date date) { this.date = date; }
      • public String getTitle() { return title; }
      • public void setTitle(String title) { this.title = title; }
      • }
    6. Create Hibernate XML Mapping
      • src/events/Event.hbm.xml
      • <?xml version=&quot;1.0&quot;?>
      • <!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;>
      • <hibernate-mapping>
      • <class name=&quot;events.Event&quot; table=&quot;EVENTS&quot;> </class>
      • </hibernate-mapping>
    7. Add Property Mappings
      • src/events/Event.hbm.xml
      • <?xml version=&quot;1.0&quot;?>
      • <!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;>
      • <hibernate-mapping>
      • <class name=&quot;events.Event&quot; table=&quot;EVENTS&quot;>
      • <id name=&quot;id&quot; column=&quot;EVENT_ID&quot;>
      • <generator class=&quot;native&quot;/>
      • </id>
      • <property name=&quot;date&quot; type=&quot;timestamp&quot; column=&quot;EVENT_DATE&quot;/>
      • <property name=&quot;title&quot;/>
      • </class>
      • </hibernate-mapping>
    8. Create Hibernate Configuration
      • src/hibernate.cfg.xml
      • <?xml version='1.0' encoding='utf-8'?>
      • <!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;>
      • <hibernate-configuration>
        • <session-factory>
        • <!-- Database connection settings -->
        • <property name=&quot;connection.driver_class&quot;>org.apache.derby.jdbc.EmbeddedDriver</property>
        • <property name=&quot;connection.url“>jdbc:derby:eventDB;create=true</property>
        • <!-- JDBC connection pool (use the built-in) -->
        • <property name=&quot;connection.pool_size&quot;>1</property>
        • <!-- SQL dialect -->
        • <property name=&quot;dialect&quot;>org.hibernate.dialect.DerbyDialect</property>
        • <!-- Enable Hibernate's automatic session context management -->
        • <property name=&quot;current_session_context_class&quot;>thread</property>
        • <!-- Disable the second-level cache -->
        • <property name=&quot;cache.provider_class&quot;>org.hibernate.cache.NoCacheProvider</property>
        • <!-- Echo all executed SQL to stdout --> <property name=&quot;show_sql&quot;>true</property>
        • <!-- Drop and re-create the database schema on startup -->
        • <property name=&quot;hbm2ddl.auto&quot;>create</property>
        • <mapping resource=&quot;events/Event.hbm.xml&quot;/>
        • </session-factory>
      • </hibernate-configuration>
    9. Create SessionFactory instance
      • src/util/HibernateUtil.java
      • package util;
      • import org.hibernate.*;
      • import org.hibernate.cfg.*;
      • public class HibernateUtil {
      • private static final SessionFactory sessionFactory;
      • static {
      • try { // Create the SessionFactory from hibernate.cfg.xml
      • sessionFactory = new Configuration().configure().buildSessionFactory();
      • } catch (Throwable ex) {
      • // Make sure you log the exception, as it might be swallowed
      • System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
      • throw new ExceptionInInitializerError(ex);
      • }
      • }
      • public static SessionFactory getSessionFactory() { return sessionFactory; }
      • }
      • Note: This can also be achieved through the Spring integration – “use the Spring OpenSessionInViewFilter which will ensure that a Hibernate Session is open” ( http:// directwebremoting.org/dwr/server/hibernate )
    10. Create an Event Manager
      • src/events/EventManager.java
      • package events;
      • import org.hibernate.Session;
      • import java.util.Date;
      • import java.util.List;
      • import util.HibernateUtil;
      • public class EventManager {
      • public void createAndStoreEvent(String title, Date theDate) {
      • Session session = HibernateUtil. getSessionFactory ().getCurrentSession();
      • session.beginTransaction();
      • Event theEvent = new Event();
      • theEvent.setTitle(title);
      • theEvent.setDate(theDate);
      • session.save(theEvent);
      • session.getTransaction().commit();
      • }
      • public List listEvents() {
      • Session session = HibernateUtil. getSessionFactory ().getCurrentSession();
      • session.beginTransaction();
      • List result = session.createQuery(&quot;from Event&quot;).list();
      • session.getTransaction().commit();
      • return result;
      • }
      • }
    11. Add the DWR servlet to web.xml
      • WebContent/WEB-INF/web.xml
      • <servlet>
      • <servlet-name>dwr-invoker</servlet-name>
      • <display-name>DWR Servlet</display-name>
      • <servlet-class>
      • org.directwebremoting.servlet.DwrServlet
      • </servlet-class>
      • <init-param>
      • <param-name>debug</param-name>
      • <param-value>true</param-value>
      • </init-param>
      • </servlet>
      • <servlet-mapping>
      • <servlet-name>dwr-invoker</servlet-name>
      • <url-pattern>/dwr/*</url-pattern>
      • </servlet-mapping>
    12. Create a Remote Proxy and Expose Remote Methods
      • Src/events/EventManager.java
      • package events;
      • import org.directwebremoting.annotations.RemoteMethod;
      • import org.directwebremoting.annotations.RemoteProxy;
      • import org.hibernate.Session;
      • import java.util.Date;
      • import java.util.List;
      • import util.HibernateUtil;
      • @RemoteProxy
      • public class EventManager {
      • @RemoteMethod
      • public void createAndStoreEvent(String title, String theDate) {
      • Session session = HibernateUtil. getSessionFactory ().getCurrentSession();
      • session.beginTransaction();
      • Event theEvent = new Event();
      • theEvent.setTitle(title);
      • theEvent.setDateString(theDate);
      • session.save(theEvent);
      • session.getTransaction().commit();
      • }
      • @RemoteMethod
      • public List listEvents() {
      • Session session = HibernateUtil. getSessionFactory ().getCurrentSession();
      • session.beginTransaction();
      • List result = session.createQuery(&quot;from Event&quot;).list();
      • session.getTransaction().commit();
      • return result;
      • }
      • }
    13. Annotate Event as a Data Transfer Object
      • src/events/Event.java
      • package events;
      • import java.text.ParseException;
      • import java.text.SimpleDateFormat;
      • import java.util.Date;
      • import org.directwebremoting.annotations.DataTransferObject;
      • import org.directwebremoting.annotations.RemoteProperty;
      • @DataTransferObject
      • public class Event {
      • @RemoteProperty
      • private Long id;
      • @RemoteProperty
      • private String title;
      • private Date date;
      • public Event() {}
      • public Long getId() {
      • return id;
      • }
      • private void setId(Long id) {
      • this.id = id;
      • }
      • @RemoteProperty
      • public String getDateString() {
      • SimpleDateFormat sdf = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;);
      • return sdf.format(this.date);
      • }
      • [continued on next slide]
    14. Annotate Event as a Data Transfer Object (con’t)
      • src/events/Event.java [continued]
      • @RemoteProperty
      • public void setDateString(String dateStr) {
      • SimpleDateFormat sdf = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;);
      • try {
      • this.date = sdf.parse(dateStr);
      • } catch (ParseException e) {
      • // TODO Auto-generated catch block
      • e.printStackTrace();
      • }
      • }
      • public String getTitle() {
      • return title;
      • }
      • public void setTitle(String title) {
      • this.title = title;
      • }
      • public Date getDate() {
      • return date;
      • }
      • public void setDate(Date date) {
      • this.date = date;
      • }
      • }
      • Note: We added getDateString and setDateString here, because there is no implicit conversion available between JavaScript dates and Java dates – mostly arrays, strings, BigNumber, and primitives. See http://directwebremoting.org/dwr/server/dwrxml/converters for more information.
    15. Update web.xml
      • WebContent/WEB-INF/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>
      • events.Event,
      • events.EventManager
      • </param-value>
      • </init-param>
      • <init-param>
      • <param-name>debug</param-name>
      • <param-value>true</param-value>
      • </init-param>
      • </servlet>
    16. Using DWR Debug Mode
      • Go to http://localhost:8080/DWRExample/dwr/
        • Click “EventManager”
        • Enter “Event 1” in the first parameter of createAndStoreEvent
        • Enter “10/01/2008” in the second parameter
      • Click the Execute button
    17.  
      • Click the Execute button next to listEvents()
    18. Let’s add DWR on the client side
      • File->New->Web->HTML-> WebContent/index.html
      • Open and edit title “DWR Example”
      • Go back to http://localhost:8080/DWRExample/dwr/test/EventManager and copy and paste the script tags
    19. More Dojo boilerplate
      • Paste the following too:
      • <script type=&quot;text/javascript&quot; src=&quot;js/dojo/dojo/dojo.js&quot;
      • djConfig=&quot;isDebug: true, parseOnLoad: true&quot;></script>
      • <link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
      • href=&quot;js/dojo/dojo/resources/dojo.css&quot; />
      • <link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
      • href=&quot;js/dojo/dijit/themes/tundra/tundra.css&quot; />
      • <link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
      • href=&quot;js/dojo/dojox/grid/_grid/Grid.css&quot; />
      • <link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
      • href=&quot;js/dojo/dojox/grid/_grid/tundraGrid.css&quot; />
      • <script type=&quot;text/javascript&quot;>
      • dojo.require(&quot;dijit.form.Button&quot;);
      • dojo.require(&quot;dijit.form.TextBox&quot;);
      • dojo.require(&quot;dijit.form.DateTextBox&quot;);
      • dojo.require(&quot;dojox.grid.Grid&quot;);
      • dojo.require(&quot;dojo.data.ItemFileReadStore&quot;);
      • dojo.require(&quot;dojoe.dojoe&quot;);
      • </script>
    20. Add Dojo.E
      • Add tundra class to body tag:
      • <body class=&quot;tundra&quot;>
      • Create XML file WebContent/dwrDojoE.xml
      • And add tag
      • <script type=&quot;text/xml&quot; dojoType=&quot;dojoe.XmlScript&quot; src=&quot;dwrDojoE.xml&quot;></script>
    21. Edit Dojo.E
      • WebContent/dwrDojoE.xml
      • <ui xmlns=&quot;html&quot; xmlns:dijit=&quot;dijit&quot; xmlns:dojox=&quot;dojox&quot;>
      • <dijit:form.Button>
      • Refresh
      • </dijit:form.Button>
      • <dojox:grid.Grid id=&quot;gridNode&quot; jsId=&quot;grid&quot; elasticView=&quot;0&quot; style=&quot;height:300px; width:500px&quot;/>
      • </ui>
    22. Where’s the Grid?!?
    23. Create a grid layout
      • WebContent/index.html
      • <body class=&quot;tundra&quot;>'
      • <script type=&quot;text/javascript&quot;>
      • var layout = [{
      • cells: [[
      • {
      • name: 'Event ID',
      • field: 'id',
      • width: 'auto'
      • },
      • {
      • name: 'Date',
      • field: 'dateString',
      • width: 'auto'
      • }, {
      • name: 'Event',
      • field: 'title',
      • width: 'auto'
      • }]]
      • }];
      • </script>
      • Note the correlation between the field values above and the RemoteProperty defintions of Event.java
    24. Add the layout to the Grid
      • WebContent/dwrDojoE.xml
      • <ui >
      • <dijit:form.Button>
      • Refresh
      • </dijit:form.Button>
      • <dojox:grid.Grid id=&quot;gridNode&quot;
      • structure=“layout”
      • jsId=&quot;grid&quot; elasticView=&quot;0&quot; style=&quot;height:300px; width:500px&quot;/>
      • </ui>
    25. Now let’s get some data
      • WebContent/index.html
      • var putEvents = function(list){
      • var dataStore = new Array;
      • dataStore[&quot;items&quot;] = list;
      • dataStore[&quot;label&quot;] = &quot;title&quot;;
      • var model = new dojox.grid.data.DojoData(null, null, {
      • jsId: 'model',
      • store: new dojo.data.ItemFileReadStore({
      • data: dataStore
      • }),
      • query: {
      • title: '*'
      • }
      • });
      • grid.setModel(model);
      • grid.refresh();
      • grid.render();
      • };
    26. Update Dojo.E
      • WebContent/dwrDojoE.xml
      • <ui>
      • <dijit:form.Button onClick=&quot;EventManager.listEvents(putEvents)&quot; >
      • Refresh
      • </dijit:form.Button>
      • <dojox:grid.Grid id=&quot;gridNode&quot; jsId=&quot;grid&quot; elasticView=&quot;0&quot; style=&quot;height:300px; width:500px&quot;/>
      • </ui>
    27. Click Refresh
    28. Create a method to create an event
      • WebContent/index.html
      • var createEvent = function(titleId, dateId){
      • var title = dojo.byId(titleId).value;
      • var date = dojo.byId(dateId).value;
      • EventManager.createAndStoreEvent(title, date);
      • EventManager.listEvents(putEvents);
      • };
    29. Let’s Add Input Controls
      • WebContent/dwrDojoE.xml
      • <ui >
      • <dijit:form.Button onClick=&quot;EventManager.listEvents(putEvents)&quot;>
      • Refresh
      • </dijit:form.Button>
      • <dojox:grid.Grid id=&quot;gridNode&quot; jsId=&quot;grid&quot; structure=&quot;layout&quot; elasticView=&quot;0“
      • style=&quot;height:300px; width:500px&quot;/>
      • <label for=&quot;eventTitle&quot; style=&quot;float: left;&quot;>Event Title:</label>
      • <dijit:form.TextBox style=&quot;float: left;&quot; id=&quot;eventTitle&quot; value=&quot;&quot;/>
      • <label for=&quot;eventDate&quot; style=&quot;float: left;&quot;>Event Date:</label>
      • <dijit:form.DateTextBox id=&quot;eventDate&quot; value=&quot;&quot; style=&quot;float: left;&quot;/>
      • <dijit:form.Button style=&quot;float: left;“
      • onclick=&quot;createEvent('eventTitle', 'eventDate')&quot; label=&quot;Add Event&quot;>
      • </dijit:form.Button>
      • </ui>
    30. Reload the page
    31. Enter a title and date
    32. Load data at startup
      • WebContent/index.html
      • dojo.addOnLoad(function() {
      • EventManager.listEvents(putEvents);
      • });
    33. Final note
      • If using more complex object models with Hibernate, use the HibernateBeanConverter3 – See http:// directwebremoting.org/dwr/server/hibernate

    + jbarciauskasjbarciauskas, 2 years ago

    custom

    4384 views, 1 favs, 2 embeds more stats

    This tutorial will walk you through the steps of cr more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 4384
      • 4339 on SlideShare
      • 45 from embeds
    • Comments 0
    • Favorites 1
    • Downloads 164
    Most viewed embeds
    • 44 views on http://joel.barciausk.as
    • 1 views on http://64.233.161.132

    more

    All embeds
    • 44 views on http://joel.barciausk.as
    • 1 views on http://64.233.161.132

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories