Skip to main content

Dynamic Ajax table example using jMaki and Java Persistence APIs on Glassfish

Posted by caroljmcdonald on February 8, 2008 at 10:52 AM PST




http-equiv="content-type">
Sample Application using jMaki and the Java Persistence APIs

a Dynamic Ajax table example using jMaki
and Java Persistence APIs on Glassfish



This Sample Catalog app demonstrates the usage of the Java
Persistence APIs to implement server side pagination (recommended for
large sets of data), and  jMaki to get and display the results in
a dynamic Ajax table.



href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555">Download
the jMaki Sample Application Code



href="https://ajax.dev.java.net/">jMaki is an Ajax framework that
provides a lightweight model for creating JavaScript centric
Ajax-enabled web applications. jMaki provides wrapped href="http://developers.sun.com/docs/web/swdp/r1/tutorial/doc/p13.html">
widgets that can be used as JavaServer Pages tags, as JavaServer
Faces components, within a Phobos application, or with PHP. This sample
applicaton uses jMaki with JavaServer Pages.


Explanation of the usage of jMaki and the Java Persistence
APIs in a sample Catalog Application

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


pagingtable.jpg src="http://weblogs.java.net/blog/caroljmcdonald/pagingtable.jpg"
height="369" width="453">


jMaki dataTable widget

With  jMaki and JavaServer Pages, you can easily include wrapped
widgets
from ajax toolkits into a JavaServer Page as a custom JSP tag. href="http://www.netbeans.org/kb/55/framework-adding-support.html">With
the Netbeans jMaki plugin you can drag  jMaki widgets from the
Palette into a JSP. jMaki standardizes widget data and event models
to simplify the
programming model and to simplify interactions between widgets.



The sample application's index.jsp page uses a jMaki yahoo.dataTable
widget to display a  list of
customers in a dynamic table.



The jMaki table widgets (there is also a jMaki dojo table
widget) are useful when you want to show a set of
results in tabular data on a web page.  Table widgets provide
sortable columns, row selection, and they can
be updated using jMaki publish subscribe events.



In the List.jsp
web page the dataTable is defined as shown below:   (Note: style="color: rgb(204, 0, 0); font-weight: bold;">Red colors
are for jMaki
tags or variables, 
and Green
for my code
or variables)


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


      name="yahoo.dataTable"

          style="color: rgb(204, 0, 0); font-weight: bold;">subscribe= style="color: rgb(204, 0, 0);">" style="font-weight: bold; color: rgb(204, 0, 0);">/table style="color: rgb(204, 0, 0);">"

          style="color: rgb(204, 0, 0); font-weight: bold;">service=" style="color: rgb(0, 102, 0);">CatalogService" style="font-weight: bold;">/>

     

     



To determine the data format and events for the
table you can refer to the  href="http://wiki.java.net/bin/view/Projects/jMakiTableDataModel">jMaki
Table Data Model or look at
the widget.json file for the table widget. This file is located in the
resources/yahoo/dataTable directory.

The service
attribute references the

 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">CatalogService 
servlet
which returns the data to be
included
in the table.  The data for the table should be a
JSON object containing an object of
columns and an array of row arrays. The column names need a unique id
which is then used in the data to associate it with a given row. An
example for a table of companies is shown below:




Code Sample from: 
 style="color: rgb(0, 0, 0);">widget.json
 style="color: rgb(204, 0, 0); font-weight: bold;">{

 'columns':[

     {'label' :'Company', 'id' : 'name'},

     {'label':'City', 'id' : 'city'}

 ],

 'rows':[

     {'name' : 'Sun Microsystems', 'city' : 'Santa
Clara'},

     
     {'name' : 'IBM', 'city' :
'Raleigh'}


 ]

}

     

     





The

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

attributes specify a topic that publish and subscribe events will be
sent to. Publish and subscribe events can be used to tie widgets
together (more on this later).



The dataTable's
 style="color: rgb(204, 0, 0); font-weight: bold;">service=" style="color: rgb(0, 102, 0);">CatalogService" style="font-weight: bold;">
 style="font-weight: bold;"> 
calls the 
 style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 102, 0);">CatalogService 
servlet
which calls the
 style="color: rgb(0, 102, 0); font-weight: bold;">getCustomersJSON style="font-weight: bold;">
method
of the Catalog
 style="color: rgb(0, 102, 0); font-weight: bold;">

class:




Code Sample from:
 style="color: rgb(0, 102, 0); font-weight: bold;">Catalog
.java
 style="font-weight: bold; color: rgb(204, 0, 0);">public class  style="color: rgb(0, 102, 0); font-weight: bold;">Catalog
{

  

 public List style="font-weight: bold; color: rgb(0, 102, 0);">getCustomers()
throws Exception {

   EntityManager
em
= getEntityManager();

   Query
q = em.createQuery(


               
"select object(o) from Customer as o");
style="font-weight: bold;">
         style="color: rgb(0, 0, 153);">q.setMaxResults(batchSize); style="font-weight: bold; color: rgb(0, 0, 153);">
        
q.setFirstResult(firstItem);


         return style="color: rgb(0, 0, 153);">q.getResultList();

 }  

     

 public JSONArray style="font-weight: bold; color: rgb(0, 102, 0);">getCustomersJSON()
throws Exception {

   JSONArray style="font-weight: bold;">customersJSON = new JSONArray();

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

   for (Customer customerData : customers) {

       JSONObject
customerJSON
= style="color: rgb(0, 102, 0); font-weight: bold;">customerData.toJSON();

       customersJSON.put(customerJSON);

   }

   return customersJSON;

 }

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

     

     


Java Persistence Query API

The Catalog 

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

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, a href="http://www.json.org/javadoc/org/json/JSONArray.html">JSONArray 
object is used to return the list in JSON format.  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.apress.com/book/bookDisplay.html?bID=10093"> 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);">
     

          ...

    public
 style="color: rgb(0, 0, 0);">JSONObject
 style="color: rgb(0, 0, 0);">  style="font-weight: bold; color: rgb(0, 102, 0);">toJSON()
{

        JSONObject thisJSON=new
JSONObject();

        thisJSON.put("name",
this.getName());

        thisJSON.put("city",
this.getCity());

        thisJSON.put("state",
this.getState());

        thisJSON.put("zip",
this.getZip());

    }

      }   

     

     



I added the

 style="font-weight: bold;"> toJSON() 
method to
the
 style="font-family: monospace;">Customer style="color: rgb(0, 0, 0);"> 
to return a JSON
representation of the
 style="font-weight: bold; color: rgb(0, 0, 0);"> style="font-family: monospace;">Customer
entity.
 style="color: rgb(0, 0, 0);">

jMaki Publish Subscribe events 

jMaki publish subscribe events tie widgets actions together. The sample
app
uses two jMaki

 style="color: rgb(204, 0, 0); font-weight: bold;">yahoo.button 
widgets
which publish to the
/button/previous,
/button/next 
 style="color: rgb(204, 0, 0); font-weight: bold;">topics
style="font-weight: bold;">
when the respective button is clicked:


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


      name="yahoo.button" value="{label : '<<',

                
action : {topic
: '/button/previous'}}"
/>

     

      name="yahoo.button" value="{label : '>>',

                
action : {topic
: '/button/next'}}"
/>

     

     



Events in jMaki are handled by href="https://ajax.dev.java.net/introGlue.html">jMaki Glue , which href="https://ajax.dev.java.net/introGlue.html"> allows JavaScript
components to talk to each
other. You put function listeners which Subscribe to topics that your
widgets Publish to in a file called glue.js (to read more about this
see A practical
guide to jMaki Events
).



Connecting the listener to the handler

 


The listener handler for the 

 style="color: rgb(0, 102, 0); font-weight: bold;">/button/next 
 style="color: rgb(204, 0, 0); font-weight: bold;">topic 
 style="color: rgb(0, 102, 0); font-weight: bold;">
is
shown below. First you declare the topic to listen to and then the
listener function which will handle the notification. The
 style="color: rgb(0, 102, 0); font-weight: bold;">/button/next 
listener
handler  increments the page number and then calls the
 style="color: rgb(0, 102, 0); font-weight: bold;">getNextPage

funtion.


Code Sample from:
 style="font-weight: bold;">glue.js
var page= 0;

     

      jmaki.subscribe(" style="color: rgb(0, 102, 0); font-weight: bold;">/button/next",
function(args) {

    page =page + 1;

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

});

     

      jmaki.subscribe(" style="color: rgb(0, 102, 0); font-weight: bold;">/button/previous",
function(args) {

    page =page - 1;

    if (page < 0) page = 0;

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

});

     

function getNextPage(page)
{

    style="color: rgb(204, 0, 0); font-weight: bold;">jmaki.doAjax({method:
"POST",

        style="color: rgb(204, 0, 0); font-weight: bold;">url: " style="color: rgb(0, 102, 0); font-weight: bold;">CatalogService?page="+encodeURIComponent(page)+

           "&rowsonly=" +
encodeURIComponent(rowsonly),

        style="color: rgb(204, 0, 0); font-weight: bold;">callback :
function(req)
{

            style="color: rgb(0, 102, 0); font-weight: bold;">customers
= eval(req.responseText);

            style="font-weight: bold; color: rgb(204, 0, 0);">jmaki.publish(" style="color: rgb(0, 102, 0); font-weight: bold;">/table/ style="color: rgb(204, 0, 0); font-weight: bold;">clear", { });

            style="color: rgb(204, 0, 0); font-weight: bold;">jmaki.publish(" style="font-weight: bold; color: rgb(0, 102, 0);">/table/ style="color: rgb(204, 0, 0); font-weight: bold;">addRows",

                  
{ value
: customers}
);

        }

    });    

}

     
       



The getNextPage
function uses 

 style="color: rgb(204, 0, 0); font-weight: bold;">jmaki.doAjax
,
which
provides an easy way to make an  XMLHttpRequest, to call the
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogService

servlet passing the page number as a URI parameter.  The 
 style="color: rgb(204, 0, 0); font-weight: bold;">callback 
function
uses  eval to convert the XMLHttpRequest response
into a JSON object. Then 
 style="color: rgb(204, 0, 0); font-weight: bold;">jmaki.publish

is called to publish the returned
 style="color: rgb(0, 102, 0); font-weight: bold;">customers

JSON object to the
 style="font-weight: bold; color: rgb(0, 102, 0);">/table/ style="color: rgb(204, 0, 0); font-weight: bold;">addRows 
topic.



The
yahoo.dataTable
widget
subscribes to the
 style="color: rgb(204, 0, 0);">
 style="color: rgb(204, 0, 0); font-weight: bold;">  style="color: rgb(0, 102, 0); font-weight: bold;">table 
topic.

Subscribe events allow you to manipulate a given instance of a widget.
The event names are appended to the the subscribe topic name following
a "/". For example  "
 style="font-weight: bold; color: rgb(0, 102, 0);">/table/ style="color: rgb(204, 0, 0); font-weight: bold;">addRows
"
will call the
 style="color: rgb(204, 0, 0); font-weight: bold;">yahoo.dataTable 
href="http://wiki.java.net/bin/view/Projects/jMakiTableDataModel">addRows
function which will add the  payload value passed to the widget to
the the table. This will cause the  returned
 style="color: rgb(0, 102, 0); font-weight: bold;">customers

JSON object to be displayed in the table on the html page.



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

method is defined as shown below:


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


public class  style="color: rgb(0, 102, 0); font-weight: bold;">CatalogServlet
extends HttpServlet {

     

protected void processRequest(HttpServletRequest request,

       HttpServletResponse response)

       throws ServletException,
IOException {

     

   Catalog
catalog = new Catalog();

   response.setContentType("text/plain;charset=UTF-8");

   PrintWriter out = response.getWriter();

   int page =

     Integer.parseInt(request.getParameter("page"));

     
   int rowsonly =

     Integer.parseInt(request.getParameter("rowsonly"));




   JSONArray array =
      catalog.getNextCustomersJSON(page);

   if (rowsonly == 1) {

     out.println(array.toString());

   } else{

     out.println("{columns
     
: [" +

        "{ label : 'Company', id :
'name'}," +

        "{ label :'City', id :
'city'}," +

        "{ label : 'State', id :
'state'}," +

        "{ label : 'Zip', id :
'zip'}" +

        "],");

     out.println("rows:
");

     out.println(array.toString());

     out.println(" }");

   }

   out.close();

}

     



The

CatalogServlet
simply calls the
 style="color: rgb(0, 102, 0); font-weight: bold;">Catalog 

class to get the next list of results from the database like we saw in
the
previous code. The
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogServlet 
then
returns the resulting
JSONArray
as a text string.



Conclusion

This concludes the sample application which demonstrates the usage of
the Java
Persistence APIs and jMaki in a dynamic Ajax table example.


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.
  • Download
    and install the href="http://www.netbeans.org/kb/55/framework-adding-support.html">jMaki
    plug-in in the NetBeans update center.


Open and Run the Sample code:

  1. Download the href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555">sample
    code and extract its contents. You should now see the newly
    extracted directory as /JPAjmaki,
    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:\JPAjmaki.


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


  3. Build the project as follows:


    • Right click the JPAjmaki node in
      the
      Projects window.
    • Select Clean and Build Project.


  4. Run the project as follows:


    • Right click the JPAjmaki 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/JPAjmaki/).





If you want to create your own jMaki
application:

  • check out Arun Gupta's href="http://blogs.sun.com/arungupta/entry/dynamic_data_in_jmaki_widgets">blog
    and screencasts. href="http://blogs.sun.com/arungupta/entry/dynamic_data_in_jmaki_widgets">

References:








Related Topics >>

Comments

this example was published February 08, 2008. jMaki probably changed something since then. Better to ask at http://forums.java.net/jive/forum.jspa?forumID=96

I'm a bit confused on this. I am working with jMaki 1.8.1.1 in NetBeans. When I reproduce your code exactly, the code seems to return an object reference and the table does not update: function returnUser(userid) { jmaki.doAjax({method: "GET", url: "UserLookup?userid=" + encodeURIComponent(userid), callback : function(req) { users = eval(req.responseText); jmaki.publish("/table/ldapusertable/clear", { }); jmaki.publish("/table/ldapusertable/addRows",{value: users}); } }); } Publish : Topic: /table/ldapusertable/clear message {} Publish : Topic: /table/ldapusertable/addRows message {value : [[object Object]]} When I remove the {value: users} wrapper and the publish looks like this, the result is the JSONArray, but the table still does not update: jmaki.publish("/table/ldapusertable/addRows",users); Publish : Topic: /table/ldapusertable/addRows message [{lastname : 'Monday' , firstname : 'Paul' , userid : '1111' , email : 'Paul.Monday@Sun.COM'}] Is there some subtle conversion I'm missing on this one? Paul

Hi Carol : I use your sample code to do a dynamic ajax table. But i encountered some problems. The following code : rows : ${catalogBean.customersJSON}} dosen't work. It just return a ["xxxx", "xxxx", "xxxx"] type of string, not the required format string like {'name' : 'Sun Microsystems', 'city' : 'Santa Clara'}. I reference to the article of Dynamic Data in jMaki Widgets Using JPA. It create a data.jsp page to provide the required format string for jMaki. What can i do to follow your method to do the same thing? Thanks.

-RestApi missing in Project. -Praful

I updated the code.

you're right, its not working anymore, I will try to update it