Skip to main content

Getting server side data into a jMaki widget

Posted by carlavmott on August 25, 2008 at 9:53 AM PDT

I got to help out with the EJB 3.1 keynote demo for JavaOne. Although the demo shows how simple it is to perform CRUD operations using EJB 3.1, this blog focuses on the communication between the client side jMaki components and server side servlet.

For more information on the new EJB features in GlassFish v3 see Mahesh's blog. The demo uses some of the latest features in EJB 3.1 and MySQL for a backend data store. I will discuss the client side code for passing data to the server and getting data from the server and displaying it in a widget. The demo shows how simple it is to perform CRUD operations using EJB 3.1.

One requirement was to use the Dojo's Fisheye widget since it looks cool and so I created a set of pages, one each for the operations create, update and delete. The appropriate page is selected using the fisheye widget so the user could provide the necessary data. Once the user submitted the data I could then send the request to the server to update the database.

In this demo, I used the Dojo fisheye widget for navigation, html forms for collecting data from the user, Yahoo dialog for displaying errors and a Dojo table to display the data. The server side code is specific to EJB 3.1 and so must run on GlassFish V3 with the EJB module installed. MySQL data base is used for storing data.

A screen shot of the demo:

crudapp.jpeg

Let's look at some of the details. The code for the index.jsp page follows. Notice that the table is getting data from the servlet "/AuthorServlet" which is returning data in JSON format. The data base is prepopulated with data so the table is rendered with some rows of data. I dropped the Yahoo dialogs in the page and made them not visible. The fisheye widget is used for navigation and there are three other pages in the application which are loaded by the dcontainer based on the selection by the fisheye. More details on that below.

<%@ taglib prefix="a" uri="http://jmaki/v1.0/jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
    <head>
        <link rel="stylesheet" href="jmaki-2column-footer.css" type="text/css"></link>
        <title>Page Title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <div id="border">
           
            <div id="header">
                <div id="banner">CRUD operations using EJB 3.1 </div>
                              
            </div> <!-- header -->

            <div id="main">
                <div id="rightColumn" style="height:600px">
                    <div id="rightColumnTop" style="height:180px">
                        <div id="rightColunmTopTable" style="height:180px">

             <a:widget
                      name="jmaki.dcontainer"
                      subscribe="/jmaki/forms"
                      value="{
                            items : [
                              { id : 'create',include : 'create.jsp', overflow : 'hidden'},
                              { id : 'update', include : 'update.jsp', overflow : 'hidden', lazyLoad : true},
                              { id : 'delete', include : 'delete.jsp', overflow : 'hidden', lazyLoad : true}
                             ]
                          }"/> 
                  </div>
                  <div id="rightColumnTopImages" style="height:180px">
                      Powered by:
                      <div>
                      <img src="images/glassfish-logo.jpg">
                  </div>
                  <div>
                      <img src="images/jmaki-seal.png">
                  </div>
                  </div>
                </div> <!-- end leftColumn -->
                <div id="rightColumnBottom" style="height:415px">
            
             <!--<center>Author Table </center>-->
            
             <a:widget name="dojo.table"
            service="/AuthorServlet" />
                   
                </div> <!-- end leftColumn -->
                                
                </div> <!-- end leftColumn -->

                <div id="leftColumn" style="height:600px">
                    <a:widget name="dojo.fisheye" args="{orientation:'vertical'}" value="[
     {iconSrc:'images/document-new.png',
      label : 'Create',
      action : { topic : '/jmaki/forms/select', message : {targetId : 'create'}}
     },
     {iconSrc:'images/edit-find-replace.png',
      label : 'Update',
      action : { topic : '/jmaki/forms/select', message : {targetId : 'update'}}
      },
      {iconSrc:'images/edit-delete.png',
      label : 'Delete',
      action : { topic : '/jmaki/forms/select', message : {targetId : 'delete'}}
      }
     ]"/>

        <a:widget id="dialog1" name="yahoo.simpledlg"args="{header : 'Error Found', visible: false, text: 'Duplicate Author Id entry found.  Provide a unique Author Id'}"
                    value="{buttons: [
        { label:'ok', isDefault:true }
        ] }"/>

        <a:widget id="dialog2" name="yahoo.simpledlg"args="{header : 'Error Found', visible: false, text:  'Author Id entry not found.  Provide a Author Id'}"
                    value="{buttons: [
        { label:'ok', isDefault:true }
        ] }"/>
         
                </div> <!-- leftColumn -->

            </div> <!-- main -->

        </div> <!-- border -->
    </body>
</html>

Now lets look at how to create an entry in the data which will be reflected in the table. First let's look at the page create.jsp.

 Enter Data to Create Author Entry: <br><br>
 
 
                  <form name="create"  >
  Author Id: <input type="text" id="authorId" name=authorId/> <br>
  Author: <input type="text" id="authorName" name=authorName/><br>
  Organization: <input type="text" id="organization" name=organization/><br>
  <br><br>
   <input type="hidden"  id="hidden" name="create" value="create">
   <input type="button" onclick="doCreate()" name="submit" value="create">
  </form>

As you can see this is a simple form which calls the doCreate function to extract the data. The doCreate function is in glue.js.

var Service="/crud/AuthorServlet";
var rowId;

function doCreate(){
    var opName = "create";
   
    var authorName = document.getElementById("authorName").value;
    var authorId = document.getElementById("authorId").value;
    var orgName = document.getElementById("organization").value;
      
      jmaki.doAjax({method: "POST",
        url: "/crud/AuthorServlet",
        content :  { authorName: authorName, authorId : authorId, orgName : orgName, opName: opName },
        callback: function(_req) {
            var tmp = _req.responseText;
    if(!tmp)  {
                 var a = jmaki.getWidget("dialog1");
                 a.setVisible(true);
            }  else {
       var obj = eval("(" + tmp + ")");
                if ( opName == "create")
                     jmaki.publish('/table/addRow', obj);
else {
    jmaki.publish('/table/updateRow', obj);
       }
   }
        },
        onerror: function() {
                 var a = jmaki.getWidget("dialog1");
                 a.setVisible(true);           
                    }
     });
     document.forms.create.reset();

}

After extracting the data from the form I use jmaki.doAjax to send the data to the server. I use the property "content" with the values I extracted because this property will pass the data to the server correctly regardless of the platform. In other words the right thing happens if the server is Java or PHP. The callback function is called if there were no errors on the server and if so the data received is passed to the table using the standard jMaki publish and subscribe mechanism. If there was an error on the server the onerror function is called and in this case I set the error dialog to visible.

Here is a screen shot of the application with the error dialog:

cruderror.jpeg

Finally I wanted to describe how the fisheye is used to display the correct form. Looking at the fisheye widget tag you see that each icon will publish to the "/jmaki/forms/select" and the payload contains a string used to identify the operation selected. The dcontainer subscribes the the "/jmaki/forms" topic. The dcontainer contains a select handler which looks up the id that it was passed, in this case 'create' and the includes the page create.jsp.

I have posted the war file on the documents and files demo area. I also have the processRequest method from the AuthorServlet code below so it is easier to see what the server is doing. There are several helper classes that update the data base or convert Java objects into JSON that are not shown.

@PersistenceUnit(name="myAuthorEMF", unitName = "WebEjbJpaPU")
public class AuthorServlet extends HttpServlet {
  
    @EJB private AuthorBean authorRef;
   
    //private AuthorHelper authorRef = new AuthorHelper();
   
    /**        
    * Processes requests for both HTTP [prettify]GET
and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { String opName = request.getParameter("opName"); int matchID = -1; Author author = null; if (opName == null) { opName = "list"; } else { author = new Author(); author.setAuthorId( Integer.valueOf(request.getParameter("authorId"))); author.setName(request.getParameter("authorName")); author.setOrganisation(request.getParameter("orgName")); } if ("update".equals(opName)) { authorRef.updateAuthor(author); } else if ("create".equals(opName)) { authorRef.createAuthor(author); } else if ("delete".equals(opName)) { authorRef.deleteAuthor(author); } sendOutData(author, opName, out); } finally { out.close(); } } [/prettify]

That's it.

Related Topics >>

Comments

very nicely explained.

I have another question, does Jmaki has the ability to show Streaming Videos ?. In one of our application we want to have a streaming video some thing like You Tube.

Hi Carla, i have sent you an e-mail, i hope in your help to understand how to configure the widgets and the glue.js...I'm a newbie and the examples are too difficult for me... the problem is that i don't understand the syntax of joining the widget in the page jsp with the glue.js. I hope in your help. Regards, Ignazio

Hi Carla, I am exploring JMaki. So far so good! Your various blog posts have been quite helpful. I have two questions though... 1. In using the jmaki.container, is there a way to get the included content from JSPs that are within the WEB-INF/ folder. In this way the JSPs are protected from external direct access. 2. Is there a way to internationalize the text-based labels of the jMaki widgets (e.g. the yahoo.button label, etc)? Thanks in anticipation! Pius

Hi Carla, thanks for the info. I want to do something very simple, but I dont found anything about it, I want to load a simple Jmaki Editor Widget with data from a database. How can I do that? I want to replace "Text" with a String object that have HTML content that is stored in a column of a Table in a DB.

Hi Suneesh. Unfortunately your only options are to poll or to use comet which will push the data to the client. Even if you can trigger the event from the database the issue is as you stated getting that to the client. I wish there was a better solution. Carla

Hello Carla, Thanks for the very helpful blogs regarding many jmaki widgets , which you have provided online. I am having an 'interesting' problem at my hands and I was wondering if you could please advise me a way around it. Problem description: I have a Jmaki Widget (a yahoo dataTable), I have been successful in retrieving value from a remote server and populating my yahoo.dataTable dynamically onLoad. I need to implement a 'PUSH' feature, where if a row is added into a table into a mysql database (the remote database) a new entry should be added into the yahoo.dataTable. Ideally I would like to avoid polling the resultset value of the tabgle under consideration. I can trigger an event from the mysql database from the remote end, but the problem comes in how to 'digest' this event and display the addition of this 'new' row in the yahoo.dataTable. Looking forward to hearing from you. Regards, Suneesh Joshi.

Hi All, I just uploaded the zip file for the NetBeans project I used to build this app. You can load it into NetBeans or look at the source directly by unzipping the file. See Crud.zip file, http://weblogs.java.net/blog/carlavmott/archive/NewCrud.zip Carla

Hi Carla , Ia ma very interested and begining to use jMaki framework . Can you please provide me the complete source code of your demo ? Thanks.