Using JSON with Dojo Toolkit

Sang Shin, sang.shin@sun.com, Sun Microsystems, www.javapassion.com


This hands-on lab takes you through the basics of using JSON data format along with Dojo Toolkit.


Expected duration: 60 minutes

Prerequisites

This hands-on lab assumes you have some basic knowledge of, or programming experience with, the following technologies.

Software Needed

Before you begin, you need to install the following software on your computer.  The Dojo Toolkit 0.3.1 is already included in the hands-on lab zip file so there is no need for you to download it yourself.


OS platforms you can use


Change Log


Lab Exercises



Exercise 1: Dojo and JSON


Note: This is the same exercise you did as part of Dojo toolkit hands-on lab (Exercise 4 of the Dojo toolkit hands-on lab).  If you already have done it, just skip this and do the homework exercise. 

In this exercise, you will learn how to use JSON as a data format of choice between the browser and the server.  (This exercise was created based on the "Using Dojo and JSON to Build Ajax Applications" article that was authored by Zarar Siddiqi with the author's permission.)

  1. Open, build, and run "Dojo and JSON" sample Dojo application using NetBeans
  2. Look under the hood of  "Dojo and JSON" sample application
  3. Add another JavaBean field called Publisher to the Book class

(1.1) Open, build, and run "Dojo and JSON" sample Dojo application using NetBeans


In this step, you are going to open a NetBeans project that is provided as part of the hands-on lab zip file, 4262_ajaxdojojson.zip.

0. Start NetBeans IDE (if you have not done so yet).
1. Select File->Open Project (Ctrl+Shift+O). The Open Project dialog box appears.
2. Browse down to <LAB_UNZIPPED_DIRECTORY>/ajaxdojojson/samples directory.
3. Select dojo-json.
4. Click Open Project Folder. (Figure-1.10 below)  The dojo-json project node appears under Projects tab window of NetBeans.


Figure-1.10: Open dojo-json project

5. Right click dojo-json project node and select Run Project.
6. Obeserve that the browser gets displayed. Move your mouse over the book titles.  You will see detailed information of  each book getting displayed. (Figure-1.11 below)


Figure-1.11: Run the dojo-json sample application

7.  If you have installed FireBug debugger and enabled "Show XMLHttpRequest" option - you can press F12 key to enable it -, you should the data being exchanged between the browser and the server.  (Figure-1.12 below) 


Figure-1.12: XMLHttpRequest data

                                                                                                              return to top of this exercise

(1.2) Look under the hood of the dojo-json sample application


In this step, you will look into various pieces that make up the dojo-json sample application.

1. Double-click BookManager.java under dojo-json->Source Packages->com.esolaria.dojoex to open it in the source editor.  (You can double-click BookManager.java tab window in the source editor to maximize the window as shown in Figure-1.20 below.  You can double-click it again to restore.)

Note that the list of Book objects are initialized.  Also it provides getBook(int bookId) method which returns a Book object.


Figure-1.20:  BookManager.java

2. Double-click Book.java under dojo-json->Source Packages->com.esolaria.dojoex to open it in the source editor.

Note the toJSONString() method uses JSONObject class through which you can create JSONObject first, which is then converted into a String. (Figure-1.21 below)


Figure-1.21: Book.java

3. Expand dojo-json->Source Packages->org.json and note that this project already has org.json.* package. (Figure-1.22 below)


Figure-1.22: org.json.* package

Now let's take a look at the client side.

4. Double-click index.jsp under dojo-json->Web Pages.  Please note that "text/json" is specified as the value of mimetype. (Code-1.23 below)

<%@ page
   import="java.util.Iterator,
           java.util.List,
           com.esolaria.dojoex.Book,
           com.esolaria.dojoex.BookManager" %>
<%
    List books = BookManager.getBooks();
%>

<html>
    <body>
    <head>
        <title>Dojo and JSON Example</title>
        <script language="javascript" src="dojo-0.3.1-ajax/dojo.js"></script>
        <script language="javascript">
            dojo.require("dojo.io.*");
            dojo.require("dojo.event.*");
            dojo.require("dojo.html.*");

            // Event handler when a user hovers a mouse over
            function trMouseOver(bookId) {
                getBookInfo(bookId);
            }
           
            // Event handler when a user hovers a mouse out
            function trMouseOut(evt) {
                var bookDiv = document.getElementById("bookInfo");
                bookDiv.style.display = "none";
            }

            // Invoked from trMoustOver(bookId) function call above
            function getBookInfo(bookId) {
                var params = new Array();
                params['bookId'] = bookId;
               
                // Perform remote operation using JSON as data format
                // that will be returned from the server
                var bindArgs = {
                    url: "actions/book.jsp",
                    error: function(type, data, evt){alert("error");},
                    mimetype: "text/json",
                    content: params
                };
                var req = dojo.io.bind(bindArgs);
               
                // The "populateDiv" gets called as an event handler
                dojo.event.connect(req, "load", this, "populateDiv");
            }

            // Function call to populate the "bookInfo" div element that is
            // defined at the end of this file.
            function populateDiv(type, data, evt) {
                var bookDiv = document.getElementById("bookInfo");
                if (!data) {
                    bookDiv.style.display = "none";
                } else {
                    bookDiv.innerHTML = "ISBN: " + data.isbn + "<br/>Author: " + data.author;
                    bookDiv.style.display = "";
                }
            }
        </script>


    </head>


    <body>
        <h1><center>Dojo and JSON Example - Move your mouse over the book titles!</center></h1>
       
        <table cellspacing="0" cellpadding="3" style="background-color:lavender; border: solid 1px #CCCCCC">
            <!-- Display each book with Id and it title in a table format -->
            <% for (Iterator iter = books.iterator(); iter.hasNext();) {
            Book book = (Book) iter.next(); %>
           
            <!-- Whenever you hover your mouse over and out on a book title,
                 trMouseOver() and trMouseOut event handlers get called -->
            <tr onmouseover="trMouseOver(<%=book.getBookId()%>)"
                onmouseout="trMouseOut(<%=book.getBookId()%>)">
                <td><%=book.getTitle()%></td>
            </tr>
            <% } %>
        </table>
       
        <!-- This is the div element that will be populated in the populateDiv
             JavaScript function above, which req object is loaded -->
        <div id="bookInfo" style="display:none;"></div>

    </body>
</html>
Code-1.23: index.jsp

5. For the sake of this exercise, let's change the mimetype to "text/plain" and see the data that is being returned from the server by inserting an alert message. (Code-1.24 below)  Note that the server still sends the data back to the client in the JSON data format.  The mimetype is the client side only attribute.

            // Invoked from trMoustOver(bookId) function call above
            function getBookInfo(bookId) {
                var params = new Array();
                params['bookId'] = bookId;
               
                // Perform remote operation using JSON as data format
                // that will be returned from the server
                var bindArgs = {
                    url: "actions/book.jsp",
                    error: function(type, data, evt){alert("error");},
                    mimetype: "text/plain",
                    content: params
                };
                var req = dojo.io.bind(bindArgs);
               
                // The "populateDiv" gets called as an event handler
                dojo.event.connect(req, "load", this, "populateDiv");
            }

            // Function call to populate the "bookInfo" div element that is
            // defined at the end of this file.
            function populateDiv(type, data, evt) {
                var bookDiv = document.getElementById("bookInfo");
                if (!data) {
                    bookDiv.style.display = "none";
                } else {
                    alert("Returned data from server in the JSON format but display in plain form = " + data);
                    bookDiv.innerHTML = "ISBN: " + data.isbn + "<br/>Author: " + data.author;
                    bookDiv.style.display = "";
                }
            }
Code-1.24: Change the mimetype to text/plain temporarily to see the data that is being returned.

6. Right click dojo-json project node and select Run Project.
7. The browser gets displayed. Move your mouse over the book titles.  You will see an alert message that display the returned data in a plain string format. Click OK to close the alert message.
8. Please note that now data.isbn and data.author is now undefined.  This is because since the data is no longer JSON JavaScript object, the values of the data.isbn and data.author are undefined. (Figure-1.25 below)


Figure-1.25: Display of the data in the JSON data format

9. Change mimetype back to "text/json" and remove the alert message.
10. Right click dojo-json project node and select Run Project and see everything is working.

                                                                                                              return to top of this exercise

(1.3) Add another field to the Book class


In this step, you are going to add another JavaBean called Publisher as a property to the Book class.  Write Publisher.java under dojo-json->Source Packages->com.esolaria.dojoex package as shown in Code-1.29 below.

package com.esolaria.dojoex;

/**
 *
 * @author sang
 */
public class Publisher {
   
    private String name;
    private String address;
    private int year;
   
    /** Creates a new instance of Publisher */
    public Publisher() {
    }
   
    public Publisher(String name, String address, int year) {
        this.name = name;
        this.address = address;
        this.setYear(year);
    }
   
    public String getName() {
        return name;
    }
   
    public void setName(String name) {
        this.name = name;
    }
   
    public String getAddress() {
        return address;
    }
   
    public void setAddress(String address) {
        this.address = address;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
   
}
Code-1.29: Publisher.java

1.  Right click com.esolaria.dojoex under dojo-json->Source Packages->com.esolaria.dojoex and select New->Java Class. For Class Name field, type in Publisher. (Figure -4.30 below) The Publisher.java file gets displayed in the source editor.


Figure-1.30: Publisher class

2. Replace the IDE generated Publisher.java with the code in Figure-3.29 above.
3. Modify Book.java under dojo-json->Source Packages->com.esolaria.dojoex package as shown in Code-1.31 below.  The code fragments that need to be added are highlighted in bold and blue-colored font.

package com.esolaria.dojoex;

import org.json.JSONObject;
import org.json.JSONException;

public class Book {
   
    private int bookId;
    private String title;
    private String isbn;
    private String author;
    private Publisher publisher;
   
    public Book(){
    }
   
    public Book(int bookId, String title, String isbn, String author, Publisher publisher) {
        this.bookId = bookId;
        this.title = title;
        this.isbn = isbn;
        this.author = author;
        this.setPublisher(publisher);
    }
   
    public String toJSONString() throws JSONException {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("bookId", new Integer(this.bookId));
        jsonObj.put("title", this.title);
        jsonObj.put("isbn", this.isbn);
        jsonObj.put("author", this.author);

        // Create a new JSONObject called jsonObj2
        JSONObject jsonObj2 = new JSONObject();
        jsonObj2.put("name", this.getPublisher().getName());
        jsonObj2.put("address", this.getPublisher().getAddress());
        jsonObj2.put("year", this.getPublisher().getYear());

        // Add the newly created jsonObj2 to jsonObj
        jsonObj.put("publisher", jsonObj2);

        return jsonObj.toString();
    }
   
    public void setBookId(int bookId) {
        this.bookId = bookId;
    }
    public int getBookId() {
        return this.bookId;
    }
   
    public void setTitle(String title) {
        this.title = title;
    }
    public String getTitle() {
        return this.title;
    }
   
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getIsbn() {
        return this.isbn;
    }
   
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getAuthor() {
        return this.author;
    }

    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }
   
}
Code-1.31: Modified Book.java

4. Modify BookManager.java under dojo-json->Source Packages->com.esolaria.dojoex package as shown in Code-1.32 below.  This is to initialize the Publisher information.  The code fragments that need to be added are highlighted in bold and blue colored font.

package com.esolaria.dojoex;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BookManager {
   
    private static List books = new ArrayList();
   
    // Initialize List of Book's'
    static {
        books.add(new Book(1, "Crime and Punishment", "0679734503", "Fyodor Dostoevsky",
                new Publisher("Google Publishing", "1 Google Land", 1900)));
        books.add(new Book(2, "The Collected Tales of Nikolai Gogol", "0375706151", "Nikolai Gogol",
                new Publisher("Yahoo Publishing", "1 Yahoo Land", 2002)));
        books.add(new Book(3, "King Rat", "0440145465", "James Clavell",
                new Publisher("Shin Company", "1 Never Land", 1899)));
        books.add(new Book(4, "The Alchemist", "0062502182", "Paulo Coelho",
                new Publisher("Daniel Company", "1 Boston", 1999)));
        books.add(new Book(5, "A Tale of Two Cities", "0451526562", "Charles Dickens",
                new Publisher("Young Publishing", "1 Dream Land",2001)));
    }
   
    public static Book getBook(int bookId) {
        Book returnValue = null;
        for (Iterator iter = books.iterator(); iter.hasNext();) {
            Book book = (Book) iter.next();
            if (book.getBookId() == bookId) {
                returnValue = book;
                break;
            }
        }
        return returnValue;
    }
   
    public static List getBooks() {
        return books;
    }
   
}
Code-1.32: Modified BookManage.java

5. Modify index.jsp under dojo-json->Web Pages as shown in Code-1.33 below. The code fragments that need to be added are highlighted in bold and blue-colored font.

<%@ page
   import="java.util.Iterator,
           java.util.List,
           com.esolaria.dojoex.Book,
           com.esolaria.dojoex.BookManager" %>
<%
    List books = BookManager.getBooks();
%>

<html>
    <body>
    <head>
        <title>Dojo and JSON Example</title>
        <script language="javascript" src="dojo-0.3.1-ajax/dojo.js"></script>
        <script language="javascript">
            dojo.require("dojo.io.*");
            dojo.require("dojo.event.*");
            dojo.require("dojo.html.*");

            // Event handler when a user hovers a mouse over
            function trMouseOver(bookId) {
                getBookInfo(bookId);
            }
          
            // Event handler when a user hovers a mouse out
            function trMouseOut(evt) {
                var bookDiv = document.getElementById("bookInfo");
                bookDiv.style.display = "none";
            }

            // Invoked from trMoustOver(bookId) function call above
            function getBookInfo(bookId) {
                var params = new Array();
                params['bookId'] = bookId;
              
                // Perform remote operation using JSON as data format
                // that will be returned from the server
                var bindArgs = {
                    url: "actions/book.jsp",
                    error: function(type, data, evt){alert("error");},
                    mimetype: "text/json",
                    content: params
                };
                var req = dojo.io.bind(bindArgs);
              
                // The "populateDiv" gets called as an event handler
                dojo.event.connect(req, "load", this, "populateDiv");
            }

            // Function call to populate the "bookInfo" div element that is
            // defined at the end of this file.
            function populateDiv(type, data, evt) {
                var bookDiv = document.getElementById("bookInfo");
                if (!data) {
                    bookDiv.style.display = "none";
                } else {
                    bookDiv.innerHTML = "ISBN: " + data.isbn + "<br/>Author: " + data.author +
                                        "<br/>Publisher Name: " + data.publisher.name +
                                        "<br/>Publisher Address: " + data.publisher.address +
                                        "<br/>Publisher Established Year: " + data.publisher.year;
                    bookDiv.style.display = "";
                }
            }
        </script>


    </head>


    <body>
        <h1><center>Dojo and JSON Example - Move your mouse over the book titles!</center></h1>
      
        <table cellspacing="0" cellpadding="3" style="background-color:lavender; border: solid 1px #CCCCCC">
            <!-- Display each book with Id and it title in a table format -->
            <% for (Iterator iter = books.iterator(); iter.hasNext();) {
            Book book = (Book) iter.next(); %>
          
            <!-- Whenever you hover your mouse over and out on a book title,
                 trMouseOver() and trMouseOut event handlers get called -->
            <tr onmouseover="trMouseOver(<%=book.getBookId()%>)"
                onmouseout="trMouseOut(<%=book.getBookId()%>)">
                <td><%=book.getTitle()%></td>
            </tr>
            <% } %>
        </table>
      
        <!-- This is the div element that will be populated in the populateDiv
             JavaScript function above, which req object is loaded -->
        <div id="bookInfo" style="display:none;"></div>

    </body>
</html>
Code-1.33: Modified index.jsp

6. Right click dojo-json project node and select Run Project.
7. Move your mouse over the titles. You should see the following result. (Figure-1.34 below)


Figure-1.34: Publisher data is also displayed

                                                                                                              return to top of this exercise

Summary


In this exercise, you have learned how to use JSON as data format of choice between backend Java application and client side browser.

                                                                                                              return to the top



Homework exercise (for people who are taking Sang Shin's "AJAX online course")


1. The homework is to modify the dojo-json project you built as Exercise #1 above as following.  (You might want to create a new project by copying the dojo-json project.)  You can name the new project in any way you want but here I am going to call to call it as dojo-json-homework
2. Send the following files to ajaxhomework@sun.com with Subject as AJAXHomework-ajaxdojojson.