DWR introduction

Thursday, December 30, 2010 Posted by Jagadeesh Manne 3 comments
What is DWR?
• Is a Java and JavaScript open source library which
allows 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
methods running on a web server just as if they
were in the browser
> Why it is called “Direct remoting”

Why DWR?
• Without DWR, you would have to create many
Web application endpoints (servlets) that need to
be address'able via URI's
• What happens 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
whether you are using XMLHttpRequest directory or clientside
only toolkit such as Dojo or Prototype
> You would have to map parameters and return values to
HTML input form parameters and responses yourself
• DWR comes with some JavaScript utility functions





  • create a web application using netbeans
  • download dwr.jar files and include them in your web-inf/lib folder. you can find these jar files in my example
  • edit web.xml to include dwr servlet 
  • create dwr.xml file to convert java class to javascript class
  • create jsp page 
  • create java class
  • call java class method using converted javascript class in jsp page
  • now execute this applicaton
 when i am doing this example i faced one problem to include those jar files in our application. i copied jar files to tomcat server lib and i executed this example.nothing happens.using google chrome inspect element i found those engine.js and util.js files not included. i have done small mistake that is instead of including dwr.jar files in web-inf/lib i included them in tomcat/lib.to find this problem i dont have net connection in home. and i dont have friends to know about dwr. after struggling one hour i removed jar files from tomcat lib and included them in web-inf/lib. why i am saying this no one cant do this mistake again. in next post i will write code about this example. you can find information about that example in comments of that code itself. if you like my explanation follow my blog.and if you have any suggestions and doubts please post your comments in blog comment form below that post. thanks and we will meet in next post  

based on my example what i observed is using dwr we can convert java class to javascript class. using this javascript class we can call java class methods in client side itself.

Creating JavaClass:

package mypack;
public class MyJavaClass
{
public String getMessage()
{
return "Wow! First DWr Example Success.hello from " +
"Jagadeesh using server" ;
}
//we will call this method
//in client side using javascript class
}

Configuring DWR servlet in web.xml
web.xml
<web-app>
<servlet>
<servlet-name>
dwr-invoker
</servlet-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>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>
here we are giving url path to dwr servlet. if you exctract dwr.jar files you can find that class in uk.ltd.getahead.dwr folder. if i learn more about dwr i will explain about this in later examples.if you know more about this xml file please post your comment below then other people can learn that

creating dwr.xml to convert java class to javascript class:
dwr.xml
<dwr>
<allow>
<create creator="new" javascript="MyJavaScriptClass">
<!-- here MyJavaScriptClass is dynamic javascript class generated by dwr-->
<param name="class" value="mypack.MyJavaClass"/>
<!-- now dwrservlet convert mypack.MyJavaClass to MyJavaScriptClass.
so we can call methods of mypack.MyJavaClass using MyJavaScritpClass-->
</create>
</allow>
</dwr>

here we are converting java class to javascript class using creator.so we can call javaclass methods using this javascript class.

Creating jsp page for frontend:
<%-- 
Document   : index
Created on : Dec 30, 2010, 9:37:30 PM
Author     : Jagadeesh
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Dwr Example</title>
<!-- You have to include these two JavaScript files from DWR -->
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<!-- This JavaScript file is generated specifically for your application -->
<!-- in dwr.xml we have converted MyJavaClass to MyJavaScriptClass.js-->
<!-- so we can call java class methods using this javascript class-->
<script type='text/javascript' src='dwr/interface/MyJavaScriptClass.js'>
</script>
<script>
function getMessageFromServer()
{
//getMessage is a method in java class. we can call this method
//using our generated javascript class
//handleReceivedData is a call back method
MyJavaScriptClass.getMessage(handleReceivedData);
}
function handleReceivedData(str)
{ 
alert(str);
}
</script>
</head>
<body onload="getMessageFromServer()">
</body>
</html>

you can read above comments to understand this concept.we have to include engine.js and util.js files and we have to include our generated javascript class using dwr.xml.that is present in dwr/interface folder.
<script type='text/javascript' src='dwr/engine.js'></script> 
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='dwr/interface/MyJavaScriptClass.js'> </script>

now execute this example and you will get message from server. if you have any doubts post your comments

Download:
Download DWR example with source 

To execute open with netbeans and run index.jsp
Labels: , ,

Softwares

Posted by Jagadeesh Manne 0 comments
following softwares uploading soon
mysql
sqlyog
mysqlconnector.jar file
Labels:

web.xml

Posted by Jagadeesh Manne 0 comments
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>
GetStates
</servlet-name>
<servlet-class>
GetStates
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
GetStates
</servlet-name>
<url-pattern>
/GetStates
</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30 
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>
Labels:

Ajax with jsp and servlet example download

Posted by Jagadeesh Manne 0 comments
Download ajax with jsp and servlet example download

To run this example 

install java and netbeans
open netbeans and open project and select this project
install mysql and install sql yog
copy mysql connect jar files to tomcat server lib folder
open sql yog and go to tools and import db.sql file 
then run index.jsp page

if you have any doubts or suggestions please submit a comment  
Labels:

DBClass.java

Wednesday, December 29, 2010 Posted by Jagadeesh Manne 0 comments
package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * * @author Jagadeesh
 * if you like this example please follow my blog and 
 * submit your comments
 */
public class DBClass {
 Connection con = null;

    public Connection createConnection() throws
                   ClassNotFoundException,SQLException
    {
        //loading the driver. to use this driver you need to include
        //mysql connector.jar files in tomcat server lib
        //install mysql and sql yog and copy jar files and import
        //database from sqlyog uisng tools-->import option
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection
             ("jdbc:mysql://localhost:3306/countrydb", "root", "root");
        return connection;
    }
    public String getStates(String country)throws 
                  SQLException, ClassNotFoundException
    {
        //creating connection by calling above method
        Connection con = createConnection();
       //using preparedstatement we are executing sql query(getting states)
        PreparedStatement pstmt = con.prepareStatement
       ("select state from countries where country=?");
        pstmt.setString(1, country);
        ResultSet rs = pstmt.executeQuery();
        String states="";
        while(rs.next())
        {
            //getting states from database
           states=rs.getString(1);
        }
        //this method returns string of states 
        return states;
    }
    public String getDistricts(String getstate)throws
                SQLException, ClassNotFoundException
    {
        //creating connection by calling above method
        Connection con = createConnection();
         //using preparedstatement we are executing sql query(getting districts)
        PreparedStatement pstmt = con.prepareStatement
        ("select Districtsnames from districts where state=?");
        pstmt.setString(1, getstate);
        ResultSet rs = pstmt.executeQuery();
        String districts="";
        while(rs.next())
        {
           districts=rs.getString(1);
        }
        //this method return districts as string.we will call this method
        //in servlet
        return districts;
    }
}
Labels:

GetStates Servlet

Posted by Jagadeesh Manne 0 comments
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import database.DBClass;
/**
 * @author Jagadeesh
 * if you like this example please submit your comments and suggestions
 * if you like this example please submit your comments and suggestions
 * if you have any doubts you can post comments in blog comment form
 */
public class GetStates extends HttpServlet {
   
    
    protected void processRequest(HttpServletRequest request, 
    HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //creating object for database class
        DBClass dbobj = new DBClass();
        String result="";
        String action = request.getParameter(("action"));
        String selectedcountry = request.getParameter("country");
        String selectedstate = request.getParameter(("state"));
      try {
           if(action.equals("getStates"))
            {
             //calling database method getstates and pass country
             // as arguement
               String state = dbobj.getStates(selectedcountry);
              //dividing states using ","
               String states[]= state.split(",");
               for(int i=0;i<states.length;i++)
               {
                   //adding states for selectbox options
                 result+="<option value="+states[i]+">"+states[i]+"</option>";
               }
               //sending result to jsp page.what ever we are
            //inserting in out.println it will go back to browser(jsp page)
               //as response

               out.println(result);
              
            }
             if(action.equals("getDistricts"))
            {
               //calling database method getstates and pass selectedstate
               // as arguement
               String districts = dbobj.getDistricts(selectedstate);
               //dividing districts using ","
               String getdistricts[]= districts.split(",");
               for(int i=0;i<getdistricts.length;i++)
               {
                   //adding districts for selectbox options
                result+="<option value="+getdistricts[i]+">"+getdistricts[i]+"</option>";
               }
                //sending result to jsp page.what ever we are
    //inserting in out.println it will go back to browser(jsp page)
               //as response
               out.println(result);
               
            }
             
            }
        catch (Exception e)
        {
            out.print(e);
        }
        finally {
            out.close();
        }
    } 
    
    @Override
    protected void doGet(HttpServletRequest request, 
    HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
    
    @Override
    protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
Labels:

index.jsp page

Posted by Jagadeesh Manne 0 comments
<%--
   @author Jagadeesh
 * if you like this example please submit your comments and suggestions
 * if you like this example please submit your comments and suggestions
 * if you have any doubts you can post comments in blog comment form
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<script>
    function GetXmlHttpObject()
{
    //creating xmlhttprequestobject.common method for any ajax application
       var xmlHttp=null;
       try
       {
          // Firefox, Opera 8.0+, Safari
          xmlHttp=new XMLHttpRequest();
       }
       catch (e)
       {
           //Internet Explorer
          try
          {
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch (e)
          {
               xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
       }
return xmlHttp;
}
//to get states
   function getStates(country)
    {
       
        xmlHttp=GetXmlHttpObject();
        if (xmlHttp==null)
        {
           alert ("Browser does not support HTTP Request")
            return
        }
        else
        {
            //sending selected country to servlet
            var url="GetStates?action=getStates&country="+country;
     //creating callback method.here countrychanged is callback method
            xmlHttp.onreadystatechange=countryChanged
            xmlHttp.open("GET",url,true)
            xmlHttp.send(null)
        }
        
    }
    //call back fuction 
function countryChanged()
{

      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
      {
          //getting response from server(Servlet)
        var showstates = xmlHttp.responseText;
        //displaying response in select box by using that id
        document.getElementById("state").innerHTML=showstates;
  //to get district for selected state getting selectedstate
   // from selectbox using that selectboxid
        var state = document.getElementById("state").value;
        // to get the districts for selected state
        getDistricts(state);

      }
}
// to get districts
 function getDistricts(state)
    {
        xmlHttp=GetXmlHttpObject();
        if (xmlHttp==null)
        {
            alert ("Browser does not support HTTP Request")
            return
        }
        else
        {
            //above we got selected state for selected country
            //now we are getting districts for selected state
            var url="GetStates?action=getDistricts&state="+state;
            //creating callback method.here stateChanged is callback method
            xmlHttp.onreadystatechange=stateChanged
            xmlHttp.open("GET",url,true)
            xmlHttp.send(null)
        }

    }
function stateChanged()
{

      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
      {
          //getting response from server(Servlet) of available districts
        var showdistricts = xmlHttp.responseText;
        //displaying district in selectbox
        document.getElementById("districts").innerHTML=showdistricts;
      }
}
</script>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
     <form method="post" name="register" id="register">
     <SELECT NAME="country" id="country"onchange="getStates(this.value)">
       <OPTION VALUE="select">select
       <OPTION VALUE="india">India
       <OPTION VALUE="US">US
       <OPTION VALUE="UK">UK
     </SELECT>
<!-- empty select box to display states-->
<SELECT NAME="states" id="state"style="width:100px" 
onchange="getDistricts(this.value)">
</SELECT>
<!-- empty select box to display districts-->
<SELECT NAME="districts" id="districts"style="width:100px" >
</SELECT>
</form>
</body>
</html>
Labels:

Ajax with JSP and Servlets Example

Posted by Jagadeesh Manne 0 comments
One person asked me how to ajax with Jsp and servlets. I am not expert in java but in this blog i am presenting what ever i know. if any drawbacks in my examples please let me know. actually i dont know much about ajax but i created a small example.This example for creating dynamic select box using ajax and jsp and servlets. for this example i used following softwares
netbeans
mysql
sqlyog(user interface for mysql)
additionally we have to include sqlconnector.jar files to execute this example
i created following pages for this example
index.jsp: frontend design for this example
GetStates.java : it is a servlet to process request
DBClass.java: It is normal java class to execute sql queries.

for this code also i used MVC same as first example.

next post i will post entire code for this example.if you read comments section in that code you can get idea about this example.if you have any doubt you can post comments in this blog. if you have any suggestions also please post comments.
Labels: , , ,