Wednesday, 5 June 2013

Direct Web Remoting: Fire an Ajax call by converting javascript objects into java objects

Hello there! I am writing the blog after longer time than expected. Actually, a thought of writing another blog post struck into my mind many times in past 15 days or so. But, when I had the thought, I did not have the time to implement and write. When I had the time, the thought was not there into my mind and bringing that thought into my mind ate up all the available time. Thankfully, today I have both thought and time available and as a result, you are reading this!

Let’s not start this blog by traditional providing the statistics way. Instead, let’s start this directly with the main contents. And I know that no one likes to read the statistics anyways because they are nothing but bull crap.

This blog talks about Ajax, the technology which is used in many web applications these days. The main advantage of this technology is to submit only required information instead of submitting the whole page to the server. A prime example of Ajax is the form which needs to be filled for signing up for an email account. Everybody remembers that desired id text box right? The one in which we write our favorite id and it says “Sorry! This id is already in use.” Then you say, “Crap! Some gobshite has already taken it.” Then you fill your second favorite id and it still says, “Haha! This is also in use...” Then again, you try another one and the cycle gets repeated. It stops by you yelling “Screw this! I am not going to sign up for this id. Their email service is shite anyways.”

We are deviating from the main topic here I guess, so let’s get back to it. People use Ajax in many web applications; there are many ways to implement it (e.g. XmlHttpRequest, Prototype js, jQuery etc...). All have different methods of passing the parameters. How about creating an object in javascript, passing it to a java method and watching it magically get converted into java object? Isn't it awesome? This is exactly what we will ponder into in this blog.

Direct Web Remoting (will be referred to DWR henceforth) provides us the way to pass the objects (multiple parameters from page) into java class and they get converted into respective instances of DTOs. Without going much into theoretical aspects of DWR, let’s start with the implementation steps. And I guess this is what everyone will be interested into.

STEP 1: Add dwr.jar and commons-logging-1.1.1.jar into lib directory of your web application. They can be downloaded from their sites dwr and apache respectively (DWR internally uses commons logging that is the only reason why we need commons-logging.jar). I have added them into my sample project. You can use those too.

STEP 2: Add the following lines into your deployment descriptor (web.xml) to make your web application aware of the DWR servlet.

 <!-- DWR Servlet start-->
    <servlet>
        <servlet-name>dwr</servlet-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</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <!-- DWR Servlet end-->

STEP 3: Create the dwr.xml file and put it into your WEB-INF directory. This file is master key to all the DWR communication/mapping. It defines the DTO which needs to be recognized as well as the class and method which needs to be called. Sample is provided below.

<dwr>
      <allow>
            <convert converter="bean" match="com.dwrtest.dto.TestDTO"></convert>
            <create creator="new" javascript="Filter">
                  <param name="class" value="com.dwrtest.action.TestAction"> </param>
                  <include method="testDWR" />
            </create>
      </allow>
</dwr>

Here, <dwr> and <allow> are the traditional opening and closing tags. Hence, we will focus on <convert>, <create>, <param> and <include> tags.

<convert>:  This tag provides the information to DWR about which javascript object needs to be converted into which java object. Here, the attribute converter=”bean” means the object passed from javascript will be converted into the object of the bean specified in “match” attribute. In this scenario, the bean specified in the “match” attribute must follow java bean specifications. We can even give * in the path. If it fails to find the class then the ajax call returns an error. Apart from bean, there are many other types of converters. They are specified here.

<create>: This tag, along with the sub tags, provides the information about which class and method needs to be called. Here, the attribute creator=”new” means the class will be instantiated using new keyword. If you are using spring IOC for instantiating the classes then, creator=”spring” needs to be used. The second attribute javascript=”Filter” means this method will be called from jsp page using Filter javascript. More on this in a shortwhile.

<param>: This tag gives information about the class whose method will be called.

<include>: This tag provides the names of the methods which  will be called using Ajax. If you have more than one method then you can specify their names in different include tags.

STEP: 4 Include the following javascripts into the page from which you are going to fire an Ajax call. These javascripts are generated dynamically and we are not supposed to give two hoots about these.

<script src='dwr/engine.js'></script>
<script src='dwr/util.js'></script>
<script src='dwr/interface/Filter.js'></script>

STEP: 5 create the methods in jsp to fire an Ajax call. The sample code is shown below:

function fireAjaxDWR(){
      var p = {
            firstName : document.getElementById("firstName").value,
            lastName : document.getElementById("lastName").value
      };
      Filter.testDWR(p,returnFromTest);
}

function returnFromTest(data){
alert(data.success);
}

Here, variable p will be converted into the instance of the bean specified in <convert> tag of dwr.xml file. First name and last name are two attributes of that bean.

The method ‘testDWR’ actually resides in the Action class (specified in the include tag in dwr.xml). The method accepts only one argument (that of type TestDTO). If you look at the call here, you will see that we have supplied two arguments. The other argument specifies the callback method (i.e. the method which will get called once the output is received). This method will be called by DWR engine once the method of action class completes its execution. The argument of this method will be the return type of that Action class’ method (in our case, it is of type TestDTO). We can access the reference variable using the dot operator as shown in the example.

Apart from specifying the call back method as an argument, we can specify the other arguments (such as timeout, the method to be called if timeout occurs etc) also. More information on this can be found on DWR website.

Voila! We are done with the sample implementation of DWR. I have created the web project and uploaded it. You can download it from here.

Finally, a special thanks to my former colleague Gaurav Saini, who taught me this awesome feature.

Happy Ajaxing! 

2 comments:

  1. Cool.. but I oppose this statement. "no one likes to read the statistics anyways because they are nothing but bull crap".

    ReplyDelete
  2. Actually, I was talking about of special case of statistics provided by me. In the previous blog posts, I have provided some statistics which are nothing but random numbers generated in my mind at the time of writing.

    ReplyDelete