Skip to main content

a Dynamic Ajax table example using dojo and RESTful Web Services on Glassfish

Posted by caroljmcdonald on July 28, 2008 at 8:47 PM PDT




http-equiv="content-type">
Sample Application using dojo, the Java API for Restful Web<br /> Services JAX-RS, and the Java Persistence APIs

a Dynamic Ajax table example using dojo and RESTful Web Services on
Glassfish



This Sample Catalog app demonstrates a RESTful Web Service, coded using
JAX-RS: Java API
for RESTful Web Services (JSR-311)
and href="http://java.sun.com/javaee/technologies/persistence.jsp">Java
Persistence API,
which provides a list
of customers, and a href="http://dojotoolkit.org/">Dojo
client which  gets and displays the Web Service responses in
a dynamic Ajax table ( href="http://dojotoolkit.org/book/dojo-book-0-9/docx-documentation-under-development/grid">Dojo
grid).



href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=9601&expandFolder=9601&folderID=8546">Download
the dojo Sample Application Code



Dojo  class="docTextHighlight">
is an open source DHTML toolkit written in JavaScript.



JAX-RS provides a
standardized API for building RESTful web services in Java. Central to
the RESTful architecture is the concept of resources identified by
universal resource identifiers (URIs). The API  provides a set of
annotations which you can add to Plain Old Java Objects (POJOs) 
to expose web resources identified by URIs .


Explanation of the usage of Dojo and JAX-RS in a sample Catalog
Application

The image below shows the Customer Listing page, which allows the user
to
page through a list of customers.

    

    table.jpg src="http://weblogs.java.net/blog/caroljmcdonald/archive/table.jpg"
height="447" width="374">



Quick installation and use of dojo with Netbeans

There are 3 ways to install dojo which you can read about in href="http://dojotoolkit.org/book/dojo-book-0-9/part-1-life-dojo/quick-installation">the
book of dojo. A quick and easy way to use dojo with Netbeans is to
download the JavaScript libraries from href="http://dojotoolkit.org/downloads">http://dojotoolkit.org/downloads.  
Create a new NetBeans Web Applications project. Extract the dojo
toolkit  into the project web directory: .../web , then rename
dojo-release-1.1.1/ to src/  this will give you the project
structure shown below.  I have already done this for the sample
project so you do not have to
download dojo in order to run the sample.


    dojonetproj.JPG src="http://weblogs.java.net/blog/caroljmcdonald/archive/dojonetproj.JPG"
height="376" width="236">

Dojo style sheets

Every page using the dojo Grid needs to import the grid style sheet

Grid.css
as
shown below:


Code Sample from: 
 style="color: rgb(0, 0, 0);">index.html


     
    


      style="font-weight: bold;">

     

     



This will load the the CSS files required by the Dojo grid widget, you
can just use  dojox/grid/_grid/Grid.css instead of tundraGrid
if you don't want the  tundra
style. 

Loading base dojo and required modules into an application

In order to load dojo into your application,  put the relative
path to the dojo.js file in a script element in the head
section of your  HTML page as shown below:


Code Sample from: 
 style="color: rgb(0, 0, 0);">index.html


     
 


      style="font-weight: bold;">

     

     



This script element will load the base dojo script which gives you
access to all the dojo functionality.



Next  the application specifies which  dojo modules to
load, using  the dojo.require function (kind of like  import
in Java):


Code Sample from:  style="font-family: monospace;">
 style="color: rgb(0, 0, 0);">index.html
 style="color: rgb(0, 0, 0);">


 

     


     



Dojo is organized into three major layers: Dojo Core, Dijit, and
DojoX.   DojoX builds on  Dojo Core and provides newer
extensions to the Dojo toolkit. The rest of the Java Script for
this application is in the file dynamicTable.js.


The Grid Widget

You can use widgets declaratively by using special attributes inside of
regular HTML tags, or programmatically through JavaScript.

The dojoType attribute declares a Dojo widget. Below is
the declaration of the Grid widget for this applicaton:

 

Code Sample from:  style="font-family: monospace;">
 style="color: rgb(0, 0, 0);">index.html
 style="color: rgb(0, 0, 0);">


style="font-weight: bold;">model="model" style="font-weight: bold;">structure="layout">



     


     



The model and structure attributes point to the  JavaScript
variables
for the model and layout structure explained below.

The Grid View

A href="http://dojotoolkit.org/book/dojo-book-0-9/docx-documentation-under-development/grid">Dojo
grid  is a widget useful for displaying data sets in a table
with its own scrollable views.  The
dojo grid widget requires a layout. A grid layout is declared as an
array of views.  Each view
is a group of columns,  declared as an array of arrays. Each array
element is an object, the "name" property
of the object names the column. The
column names will be displayed in the top row of the grid. The code
below declares 4 columns: Company class="userinput">, City,
State, Zip
. This grid layout
structure consists of one view as shown  below:


Code Sample from: 
 style="color: rgb(0, 0, 0);">dynamicTable.js


     

// Data Grid layout
// A grid view is a group of columns

var view1 = {

           
cells: [

               
[

                   
{name: 'Company', field: "name"},

                   
{name: 'City', field: "city"},

                   
{name: 'State',field: "state"},

                   
{name: 'Zip',field: "zip"}

               
]

            ]

};

// a grid layout is an array of views.

var layout = [ view1 ];

     

     



This grid layout for this example is shown in the figure below (note:
how the data for the table gets loaded is explained below).

    dojogrid.JPG src="http://weblogs.java.net/blog/caroljmcdonald/archive/dojogrid.JPG"
height="199" width="352">


The Grid Model

The dojo grid widget requires a data model. The model variable declares
the type of Dojo object that the Grid will use for the json data that
will be loaded in the grid. There are different href="http://dojotoolkit.org/book/dojo-book-0-9/docx-documentation-under-development/grid/model-options">options
for the model, this example uses the

dojox.grid.data.Objects
which is a collection of objects to be displayed in the grid.


Code Sample from:  style="font-family: monospace;">
 style="color: rgb(0, 0, 0);">dynamicTable.js
 style="color: rgb(0, 0, 0);">


// the model will contain the data to be displayed in the view

model = new dojox.grid.data.Objects(null,null);

     

function handleResponse(responseObject,
ioArgs){

    // set the model object with the returned customers
list

   
model.setData(responseObject.customers.customer);  
    

}  

     

// make request to the customers web service

function loadTable(page){

    start = page * batchSize;

    var targetURL = "resources/customers/?start="+
encodeURIComponent(start);   

    dojo.xhrGet({

        url: targetURL,

        handleAs: "json",

        load: handleResponse,

        error: handleError

    });

}

     



The loadTable
function calls   dojo.xhrGet to
make an XMLHttpRequest to the customers JAX-RS web
service specified by the url: parameter. When the
response from web service is returned, the callback function 

handleResponse
specified by load:
is
called and the response is passed to the callback function in the responseObject.
The handleAs  parameter specifies
the response data type, handleAs: "json" 
means
the returned data is of the type JSON (Java Script object notation).

In the  
handleResponse callback
function, 
model.setData
is called to populate the Dojo
grid  with the data returned from the 
 the 
customers
JAX-RS web service. Below is an example of a
JSON response from the customers
JAX-RS web service:


Example json data
 style="color: rgb(0, 0, 0);">


{"customers":

  {"@uri":"http://host/dojoRest/resources/customers/",

   "customer":[

    
{"@uri":"http://host/dojoRest/resources/customers/1/",

       "name":"JumboCom",

      "city":"Fort
Lauderdale",     

       "state":"FL",

       "zip":"33015"},

    
{"@uri":"http://host/dojoRest/resources/customers/2/",

       "name":"Livermore Enterprises",

       "city":"Miami",

       "state":"FL",

       "zip":"33055"}

    ]

  }

}


     

     


Loading the table

The dojo.addOnLoad function allows you to call a 
function after a page has loaded and after Dojo has finished its
initilization. This application uses dojo.addOnLoad to
call the loadTable() function (which we looked at
above)  which calls the  customers JAX-RS web
service and sets the results in the grid data model.


Code Sample from:  style="font-family: monospace;">
 style="color: rgb(0, 0, 0);">dynamicTable.js


   

     

     

 

Events for paging

The  "<<"">>" buttons
call the next() previous() functions when
clicked:


Code Sample from: 
  style="color: rgb(0, 0, 0);">index.html










     

     



The next()

 style="color: rgb(0, 102, 0); font-weight: bold;"> 
function 
increments the page number and then calls the loadTable()
funtion:


Code Sample from:
 style="color: rgb(0, 0, 0);"> dynamicTable.js


     

      function
next() {

    page =page + 1;

    loadTable(page);

}

     

function previous() {

    page =page - 1;

    if (page < 0) page = 0;

    loadTable(page);

}

     


RESTful  Web Services with JAX-RS



The  dojo.xhrGet  url:
parameter  references the style="font-weight: bold;"> URI  resources/customers/

 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">
 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);"> 
for the
 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">customers 
 
RESTful web service.  The customers
 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">
RESTful web
service was generated using Netbeans 6.1 as explained in the href="http://www.netbeans.org/kb/61/websvc/rest.html">Generating
RESTful Web Services from Entity Classes  tutorial. 
Using Netbeans 6.1 you can generate JPA Entity Classes from Database
tables, then you can Generate RESTful Web Services from Entity
Classes, and then you can test the Web Services with a browser
interface. The customers
 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">
RESTful web
service was generated from the customer data table which comes already
created in the Java DB with Netbeans. 



Below is a snippet from the
 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersResource
.java
class which was generated by the Netbeans "Generate RESTful Web
Services
from Entity Classes" feature :


Code Sample from:
 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersResource
.java


      // Service URI path
"/customers/"
style="color: rgb(0, 0, 153); font-weight: bold;">

@Path("/customers/")

public class CustomersResource
{

  

         style="font-weight: bold;">  @GET style="color: rgb(0, 0, 153); font-weight: bold;"> style="font-weight: bold;">
          style="color: rgb(0, 0, 153); font-weight: bold;">@ProduceMime("application/json")

    public
CustomersConverter
      get( style="color: rgb(0, 0, 153); font-weight: bold;">@QueryParam("start")

            style="color: rgb(0, 0, 153); font-weight: bold;">@DefaultValue("0")
int start, @QueryParam("max")

           
@DefaultValue("4") int max, @QueryParam("expandLevel")

           
@DefaultValue("1") int expandLevel, @QueryParam("query")

           
@DefaultValue("SELECT e FROM Customer e") String query) {

        try {

           
CustomersConverter custs = new CustomersConverter(

               
      getEntities(start,
max, query),

               
context.getAbsolutePath(), expandLevel);

           
return
custs
;

        } finally {

           
PersistenceService.getInstance().close();

        }

    }

      style="color: rgb(0, 0, 153); font-weight: bold;"> style="font-family: monospace;">


     



The CustomersResource
represents a list of customers. The

 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersResource
 
get method
returns a list of Customer objects in JSON
format. 

  • To address a resource in REST you specify its URI. 
     style="color: rgb(0, 0, 153); font-weight: bold;">@Path 
    is
    a JAX-RS annotation that identifies the URI path for the resource. For
    the CustomersResource 
    the URI path is /
     style="color: rgb(0, 0, 153); font-weight: bold;"> style="color: rgb(0, 102, 0);">customers
    /.
     style="color: rgb(0, 0, 153);"> 

       
  •  style="font-weight: bold;">@GET 
    specifies
    that the
    get
       
    method supports the HTTP GET method.
     style="color: rgb(0, 0, 153); font-weight: bold;">
  • @ProduceMime
       
    specifies the MIME types that a method can produce.
    Here,
    the annotation specifies that the
     style="color: rgb(0, 102, 0); font-weight: bold;">get

    method returns a JSONArray object.  The
     style="color: rgb(0, 102, 0); font-weight: bold;">CustomersConverter
       
    class is a JAXB
    annotated class which is used to marshal a list of Customer objects
    into XML or href="http://wikis.sun.com/display/Jersey/JSON+support+in+JAXB">JSON
    format.   The
     style="font-weight: bold; color: rgb(0, 102, 0);">getEntities 
     style="color: rgb(0, 102, 0); font-weight: bold;">
    method
    returns a list of Customer entity objects and is explained
    below.  
     style="color: rgb(0, 0, 153); font-weight: bold;">
  • @QueryParam
       
    specifies
    input parameters for methods.  When the method is invoked, the
    input value will be injected into the corresponding input
    argument. 
     style="color: rgb(0, 0, 153); font-weight: bold;">
  • @DefaultValue
       
    specifies a default value for an arguement if no
    input
    value is given.

Here is an example of an HTTP request for this Web Service:


Request: GET
http://host/dojoRest/resources/customers/?start=0




Here is an example of an HTTP response for this Web Service:


Received:

{"customers":

  {"@uri":"http://host/dojoRest/resources/customers/",

   "customer":[

    
{"@uri":"http://host/dojoRest/resources/customers/1/",

       "name":"JumboCom",

      "city":"Fort
Lauderdale",     

       "state":"FL",

       "zip":"33015"},

    
{"@uri":"http://host/dojoRest/resources/customers/2/",

       "name":"Livermore Enterprises",

       "city":"Miami",

       "state":"FL",

       "zip":"33055"}

    ]

  }

}





The CustomersConverter
class is a JAXB annotated
class, used to marshal a list of Customer objects into XML or 
JSON format.  A snippet of the

 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersConverter

class is shown below:




Code Sample from:
 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersConverter
.java
 style="font-weight: bold; color: rgb(204, 0, 0);"> style="color: rgb(0, 0, 153); font-weight: bold;">

      @XmlRootElement

public class CustomersConverter {

     

    style="color: rgb(0, 0, 153); font-weight: bold;">@XmlElement

    public Collection
getCustomer(){

      style="color: rgb(0, 0, 0);">   style="font-weight: bold;">    
...


            
return items;


          }

    @XmlAttribute

    public URI
getUri() {


             
return uri;


          }

      style="color: rgb(0, 0, 153); font-weight: bold;"> style="font-family: monospace;">


     




Java Persistence Query API

The CustomersResource

 style="color: rgb(0, 102, 0); font-weight: bold;"> 
getEntities
method

uses the Java Persistence API style="color: rgb(204, 0, 0);">
Query
 style="color: rgb(204, 0, 0); font-weight: bold;"> 
object
to return a list of customers.


Code Sample from:
 style="color: rgb(0, 102, 0); font-weight: bold;">CustomersResource
.java
 style="font-weight: bold; color: rgb(204, 0, 0);"> style="color: rgb(0, 0, 153); font-weight: bold;">

@Path("/customers/")

public class CustomersResource
{

  

          .
. .

      style="color: rgb(0, 0, 153); font-weight: bold;"> style="font-family: monospace;">

    protected Collection style="font-weight: bold;">getEntities(int
start, int max, String query) {

       
PersistenceService
ps =
PersistenceService.getInstance();

        Query query = ps.
createQuery(query);

        query.
setFirstResult(start);

     
        query.setMaxResults(max);

        return query.
getResultList();

    }

     


 

     



The Java
Persistence href="http://java.sun.com/javaee/5/docs/api/javax/persistence/Query.html">Query
APIs are used to create and execute queries that can return a
list of results.  The JPA Query interface provides
support for pagination via the setFirstResult() and setMaxResults()
methods: query. style="color: rgb(0, 0, 0);">setMaxResults(int maxResult)
sets the maximum number of results to retrieve. style="font-family: mon;"> query. style="color: rgb(0, 0, 0);">setFirstResult(int startPosition)
sets the position of the first result to retrieve.




In the code below, we show the

 style="color: rgb(0, 102, 0); font-weight: bold;">Customer

entity class which maps to the  CUSTOMER table that stores the
customer instances. This is a
typical Java Persistence entity object. There are two requirements for
an entity:

  1. annotating the class with an
     style="font-weight: bold; color: rgb(0, 0, 153);">@Entity

    annotation.
  2. annotating the primary key identifier with @Id
     


Because the fields name, description.... are basic mappings from the
object fields to columns of the same name in the database table, they
don't have to be annotated. 

For more information on Netbeans and JPA see href="http://www.netbeans.org/kb/55/persistence.html">basics of
developing a web application using Java™ Persistence API.






 
   
     
Code Sample from: style="color: rgb(0, 102, 0); font-weight: bold;">Customer.java


      @Entity style="color: rgb(0, 0, 0);">
      style="color: rgb(0, 0, 0);">

      public class style="font-weight: bold; color: rgb(0, 102, 0);"> style="font-family: monospace;">Customer style="color: rgb(0, 0, 0);">
implements Serializable {

     

         
@Id
  

    private Integer customerId;


    private String name;

    private String addressline1;   

    private String city;  

    private String state; 

    private String zip;


          

    public
 style="font-weight: bold;">Customer
() { }

     

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }
 style="color: rgb(0, 0, 0);">
     

     
 style="color: rgb(0, 0, 0);"> 

      }   

     

     
 style="font-weight: bold;">






Conclusion

This concludes the sample application which  demonstrates a
RESTful Web Service, coded using
JAX-RS: Java API
for RESTful Web Services (JSR-311)
,
which provides a list
of customers, and a dojo
client which  gets and displays the Web Service responses in
a dynamic Ajax table.

Configuration of the Application
for jMaki, JPA, Netbeans 6.1 and Glassfish V2

  • Download
    and install NetBeans 6.1 bundled with GlassFish V2
  • Alternatively you can  href="https://glassfish.dev.java.net/public/downloadsindex.html">Download
    and install GlassFish V2 separately.


Open and Run the Sample code:

  1. Download the href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=9601&expandFolder=9601&folderID=8546">sample
    code and extract its contents. You should now see the newly
    extracted directory as /dojoRest,
    where is the directory where
    you installed the sample package. For example, if you extracted the
    contents to C:\ on a Windows machine, then your newly
    created directory should be at C:\dojoRest.


  2. Start the NetBeans IDE. Click Open Project in the File menu and
    select the dojoRest directory you just
    unzipped.


  3. Build the project as follows:


    • Right click the dojoRest
       node in
      the
      Projects window.

           

    •      
    • Select Clean and Build Project.

             

           

    •    

     

  4.  
  5. Run the project as follows:

       

       

           
    • Right click the dojoRest node in
      the
      Projects window.
    • Select Run Project.

When you run the project, your browser should display the opening page
of the Sample Application (at
http://localhost:8080/dojoRest/).


References:








Related Topics >>