Using Dojo Toolkit  Widgets

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


In this hands-on lab, you are going to learn how to use Dojo toolkit widgets first and then how to associate event handlers to the widgets.

Expected duration: 90 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.4.3 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


Things to be done (by Sang Shin)


Lab Exercises


Exercise 1: Usage of Built-in Widgets

Dojo toolkit comes with many useful ready-to-use widgets.  In this exercise, you will learn how to use these widgets.  In subsequent exercises, you will learn how to create your own widgets.


(1.1) Create a new project called "dojo-widget-datepicker" by copying the "dojo-event1"  project you created above

1. Right click dojo-event1 project and select Copy Project.  The Copy Project dialog box appears.
2. In the Project Name: field, type in dojo-widget-datepicker.  The copying project might take a couple of minutes. The dojo-widget-datepicker project appears under Projects tab window.
3. Right-click dojo-widget-datepicker project and select Properties.  The Project Properties dialog box appears,
4. Select Run and change the Context Path: field to /dojo-widget-datepicker.


(1.2) Use datePicker widget from Dojo toolkit

We are now going to modify the index.jsp in which we are going to use datePicker widget from Dojo toolkit.

1. Double-click the index.jsp file of the dojo-widget-datepicker project to open it in the  source editor.  Please make sure you do not change the index.jsp file of the other projects - they all share the same file name, index.jsp.

2. Replace the complete content of the index.jsp file with the following code (Code-3.20 below).  Please study how widget is included, which is highlighted in bold-font.

<html>
    <head>
        <script language="JavaScript"
            type="text/javascript"
            src="dojo-0.4.3-ajax/dojo.js">               
        </script> 
 
        <!-- Dojo is loaded, include the widgets  -->
        <script>
            dojo.require("dojo.widget.DatePicker");
            dojo.require("dojo.widget.DropdownDatePicker");
        </script>
        <style>
            body {
            font-family: Arial, Helvetica, sans-serif;
            padding: 0;
            margin: 0;
            }

            .page {
            padding: 10px 10px 10px 10px;
            }
        </style>       

        <title>Usage of datePicker Widget from Dojo Toolkit</title>
    </head>
    <body>
 
        <h1><center>Usage of datePicker Widget from Dojo Toolkit</center></h1>
        <hr/>
        <table>
            <tbody>
                <tr>
                    <td style="vertical-align:top;">
                        <h4>In document:</h4><div dojoType="datepicker" widgetId="foo"></div>
                    </td>
                    <td style="vertical-align:top;">               
                        <form action="" onsubmit="return false;">
                                        <h4>Dropdown:</h4>
                            <div dojoType="dropdowndatepicker"></div>
                        </form>
                    </td>
                </tr>
            </tbody>
        </table>       
 
    </body>
</html>

2. Right click dojo-widget-datepicker project node and select Run Project.  You should see the following. (Figure-3.21 below)


Figure-1.21: Usage of datePicker widget

                                                                                                                                   return to top of this exercise

(1.3) Create a new project called "dojo-widget-fisheye" by copying the "dojo-widget-datepicker"  project you created above

1. Right click dojo-widget-datepicker project and select Copy Project.  The Copy Project dialog box appears.
2. In the Project Name: field, type in dojo-widget-fisheye.  The copying project might take a couple of minutes. The dojo-widget-fisheye project appears under Projects tab window.
3. Right-click dojo-widget-fisheye project and select Properties.  The Project Properties dialog box appears,
4. Select Run and change the Context Path: field to /dojo-widget-fisheye.


(1.4) Use FisheyeList and FisheyeItem widgets from Dojo toolkit

We are now going to modify the index.jsp in which we are going to use FisheyeList and FisheyeItem widgets from Dojo toolkit.

1. Double-click the index.jsp file of the dojo-widget-fisheye project to open it in the  source editor.  Please make sure you do not change the index.jsp file of the other projects - they all share the same file name, index.jsp.

2. Replace the complete content of the index.jsp file with the following code (Code-3.40 below).  Please study how widget is included, which is highlighted in bold-font.  If you want to display different images, just replace the value of dojo:iconsrc attributes accordingly.

<html>
    <head>
        <script language="JavaScript"
            type="text/javascript"
            src="dojo-0.4.3-ajax/dojo.js">               
        </script> 
 
        <!-- Dojo is loaded, include the widget  -->
        <script>
            dojo.require("dojo.widget.FisheyeList");
            dojo.hostenv.writeIncludes();
        </script>
       
        <script>
            function load_app(id){
            alert('Icon '+id+' was clicked');
            }
        </script>

        <style>

            .dojoHtmlFisheyeListBar {
            margin: 0 auto;
            text-align: center;
            }

            .outerbar {
            background-color: #666;
            text-align: center;
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            }

            body {
            font-family: Arial, Helvetica, sans-serif;
            padding: 0;
            margin: 0;
            }

            .page {
            padding: 60px 20px 20px 20px;
            }

        </style>       

        <title>Usage of FisheyeList & FisheyeItem Widgets from Dojo Toolkit</title>
    </head>
    <body>
 
        <h1><center>Usage of FisheyeList & FisheyeItem Widgets from Dojo Toolkit - Move your mouse over the images!</center></h1>
        <hr/>
       
        <div class="dojo-FisheyeList"
            dojo:itemWidth="50" dojo:itemHeight="50"
            dojo:itemMaxWidth="200" dojo:itemMaxHeight="200"
            dojo:orientation="horizontal"
            dojo:effectUnits="2"
            dojo:itemPadding="10"
            dojo:attachEdge="top"
            dojo:labelEdge="bottom"
            dojo:enableCrappySvgSupport="false"
            >
       
            <div class="dojo-FisheyeListItem" onmouseover="load_app(1);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_browser.png"
                dojo:caption="Browser" >
            </div>
       
            <div class="dojo-FisheyeListItem" onmouseover="load_app(2);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_calendar.png"
                dojo:caption="Calendar" >
            </div>
       
            <div class="dojo-FisheyeListItem" onmouseover="load_app(3);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_email.png"
                dojo:caption="Email" >
            </div>
       
            <div class="dojo-FisheyeListItem" onmouseover="load_app(4);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_texteditor.png"
                dojo:caption="Text Editor" >
            </div>
       
            <div class="dojo-FisheyeListItem" onmouseover="load_app(5);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_update.png"
                dojo:caption="Update" >
            </div>  
 
        </div>       

 
    </body>
</html>

3. Right click dojo-widget-fisheye project node and select Run Project.  You should see the following. (Figure-1.41 below)


Figure-1.41: Usage of FisheyeList and FisheyeItem widgets from Dojo toolkit

                                                                                                                                   return to top of this exercise

(1.5) Create a new project called "dojo-widget-editor" by copying the "dojo-widget-datepicker"  project you created above

1. Right click dojo-widget-datepicker project and select Copy Project.  The Copy Project dialog box appears.
2. In the Project Name: field, type in dojo-widget-editor.  The copying project might take a couple of minutes. The dojo-widget-editor project appears under Projects tab window.
3. Right-click dojo-widget-editor project and select Properties.  The Project Properties dialog box appears,
4. Select Run and change the Context Path: field to /dojo-widget-editor.


(1.6) Use Editor widget from the Dojo toolkit

We are now going to modify the index.jsp in which we are going to use Editor widget from Dojo toolkit.

1. Double-click the index.jsp file of the dojo-widget-editor project to open it in the  source editor.  Please make sure you do not change the index.jsp file of the other projects - they all share the same file name, index.jsp.

2. Replace the complete content of the index.jsp file with the code below.  Please study how widget is included, which is highlighted in bold-font. 

<html>
    <head>
        <script language="JavaScript"
            type="text/javascript"
            src="dojo-0.4.3-ajax/dojo.js">               
        </script> 
 
        <!-- Dojo is loaded, include the widget  -->
        <script>
            dojo.require("dojo.widget.Editor");
        </script>
       <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            padding: 0;
            margin: 0;
        }

        .page {
            padding: 10px 10px 10px 10px;
        }
       </style>       

        <title>Usage of Editor Widget from Dojo Toolkit</title>
    </head>
    <body>
 
        <h1><center>Usage of Editor Widget from Dojo Toolkit</center></h1>
        <hr/>
        <div dojoType="Editor"
                 items="formatblock;|;insertunorderedlist;insertorderedlist;|;bold;italic;underline;strikethrough;|;createLink;">

        <p>This <b>is</b> <i>the</i> text inside the editor.  Go ahead and edit it.</p>
                <p>
                   This example shows the usage of Editor widget from Dojo toolkit.
                </p>
        </div>
 
    </body>
</html>

3. Right click dojo-widget-editor project node and select Run Project.  You should see the following. (Figure-1.61 below)


Figure-1.61: Usage of Editor widget

4. Edit the contents inside the browser using different fonts as shown below. (Figure-1.62 below)


Figure-1.62: Editor contents with the browser.

                                                                                                                                   return to top of this exercise


(1.7) Try other widgets that come with Dojo toolkit


1. From you browser, go to http://localhost:8080/dojo-widget-editor/dojo-0.4.3-ajax/demos/widget/.  You will see the list of various widgets. (Figure-1.70 below)


Figure-1.70: List of widgets that come with

2. Click rounded.html. You should see the following (Figure-1.71 below)


Figure-1.71: Usage of Rounded box widget

3. From the browser, select View and then select Page Source (Ctrl+U).  (Figure-1.72 below.)


Figure-1.72: Take a look at the page source

4. You should see the page source. (Figure-1.73 below)


Figure-1.73: Page source

You can now see how Rounded box widget is used in a page. 

4. Create a NetBeans project in which you use Rounded box widget.
5. Play around with other widgets that come with Dojo toolkit.

                                                                                                              return to top of this exercise


Summary


In this exercise, you have learned how to use various widgets that are provided by Dojo toolkit.

                                                                                                                     return to the top

Exercise 2: Dojo and JSON


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
  4. Add another JavaBean field of your own to the Book class for your own exercise
Solution: The solution to this exercise is available as a ready-to-open-and-run NetBeans project, <LAB_UNZIPPED_DIRECTORY>/ajaxdojowidget/solutions/dojo-json-solution1.  You can just open it and run it.

For further information on JSON, please go to the following sites:

(2.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, 4267_ajaxdojowidget.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>/ajaxdojowidget directory.
3. Select dojo-json.
4. Click Open Project Folder. (Figure-2.10 below)  The dojo-json project node appears under Projects tab window of NetBeans.


Figure-2.10: Open dojo-json project

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


Figure-2.41: Run the dojo-json sample application

7.  If you have installed FireBug debugger and enabled "Show XMLHttpRequest" option, you should the data being exchanged between the browser and the server - press F12 in order to open FireBug debugger.  (Figure-2.42 below)  For the description on how to enable "Show XMLHttpRequest" option of the FireBug, please see here.


Figure-2.42: XMLHttpRequest data

                                                                                                              return to top of this exercise

(2.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 in the source editor.  (You can double-click BookManager.java tab window in the source editor to maximize the window as shown in Figure-2.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-2.20:  BookManager.java

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

Note the toJSONString() method uses JSONObject class through which you can create data in the JSON format. (Figure-2.21 below)


Figure-2.21: Book.java

3. Expand dojo-json->Source Packages->org.json and note that this project already has org.json.* package in the source code format. (Figure-2.22 below)


Figure-2.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-2.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.4.3-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-2.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-2.24 below)  Note that the server still sends the data back to the client in the JSON data format.

            // 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-2.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-2.25 below)


Figure-2.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

(2.3) Add another field to the Book class


In this step, you are going to add another JavaBean field to the Book class.  You are going to write Publisher.java under dojo-json->Source Packages->com.esolaria.dojoex package in the steps described below.

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.29 below) The Publisher.java file gets displayed in the source editor.


Figure-2.29: Publisher class

2. Replace the IDE generated Publisher.java with the code in Figure-2.30 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-2.30: Publisher.java

3. Modify Book.java under dojo-json->Source Packages->com.esolaria.dojoex package as shown in Code-2.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);
        JSONObject jsonObj2 = new JSONObject();
        jsonObj2.put("name", this.getPublisher().getName());
        jsonObj2.put("address", this.getPublisher().getAddress());
        jsonObj2.put("year", this.getPublisher().getYear());
        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-2.31: Modified Book.java

4. Modify BookManager.java under dojo-json->Source Packages->com.esolaria.dojoex package as shown in Code-2.32 below.  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-2.32: Modified BookManage.java

5. Modify index.jsp under dojo-json->Web Pages as shown in Code-2.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.4.3-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-2.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-2.34 below)


Figure-2.34: Publisher data is also displayed

                                                                                                              return to top of this exercise

 

Solution to this exercise


The solution to this exercise is available as ready-to-open-and-run NetBeans project <LAB_UNZIPPED_DIRECTORY>/ajaxdojowidget/solutions/dojo-json-solution1.  You can just open it and run it.

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


Exercise 3: Modify "Dojo and JSON" sample application from Exercise 4 to use Dojo Fisheye widget

In this exercise, you are going to modify "Dojo and JSON" sample application (dojo-json project under NetBeans) you built in Exercise 4 to use Fisheye widget.  More precisely what you are going to do here is to retrieve the book data from the server whenever you hover your mouse over an icon.

  1. Add Fisheye widget to the application

(3.1) Add Fisheye widget to the application


1.  Modify index.jsp under dojo-json->Web Pages as shown in Code-2.50 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.4.3-ajax/dojo.js"></script>
        <script language="javascript">
            dojo.require("dojo.io.*");
            dojo.require("dojo.event.*");
            dojo.require("dojo.html.*");

            // Add Fisheye packages
            dojo.require("dojo.widget.FisheyeList");
            dojo.hostenv.writeIncludes();

            // 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 = "";
                }
            }

            // Add event handler function for Fisheye widget
            function load_app(bookId){
                getBookInfo(bookId);
            }

        </script>

       <!-- Add new style for Fisheye widget -->
       <style>

            .dojoHtmlFisheyeListBar {
            margin: 0 auto;
            text-align: center;
            }

            .outerbar {
            background-color: #666;
            text-align: center;
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            }

            body {
            font-family: Arial, Helvetica, sans-serif;
            padding: 0;
            margin: 0;
            }

            .page {
            padding: 60px 20px 20px 20px;
            }

        </style>      


    </head>


    <body>
        <h1><center>Dojo and JSON and FishEye Example - Move your mouse over the book titles or Icons!</center></h1>
      
          <div class="dojo-FisheyeList"
            dojo:itemWidth="50" dojo:itemHeight="50"
            dojo:itemMaxWidth="200" dojo:itemMaxHeight="200"
            dojo:orientation="horizontal"
            dojo:effectUnits="2"
            dojo:itemPadding="10"
            dojo:attachEdge="top"
            dojo:labelEdge="bottom"
            dojo:enableCrappySvgSupport="false"
            >
      
            <div class="dojo-FisheyeListItem" onmouseover="load_app(1);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_browser.png"
                dojo:caption="Browser" >
            </div>
      
            <div class="dojo-FisheyeListItem" onmouseover="load_app(2);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_calendar.png"
                dojo:caption="Calendar" >
            </div>
      
            <div class="dojo-FisheyeListItem" onmouseover="load_app(3);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_email.png"
                dojo:caption="Email" >
            </div>
      
            <div class="dojo-FisheyeListItem" onmouseover="load_app(4);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_texteditor.png"
                dojo:caption="Text Editor" >
            </div>
      
            <div class="dojo-FisheyeListItem" onmouseover="load_app(5);"
                dojo:iconsrc="dojo-0.4.3-ajax/demos/widget/images/icon_update.png"
                dojo:caption="Update" >
            </div>  
        </div>      

        <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-3.10: Modified index.jsp

2. Right click dojo-json project node and select Run Project.  Firefox browser gets displayed.
3. Move your mouse over the icons. You should see the following result.  (Figure-5.11 below)  The book data is retrieved from the server automatically when you hover your mouse over the icons.  Each icon should result in different book data.


Figure-5.11: Use Fisheye widget to retrieve the data from the server

                                                                                                                                                return to the top

Solution to this exercise


The solution to this exercise is available as ready-to-open-and-run NetBeans project <LAB_UNZIPPED_DIRECTORY>/ajaxdojowidget/solutions/dojo-json-solution2.  You can just open it and run it.

Summary


In this exercise, you have learned how to use attach event handlers to the Dojo fisheye widgets.


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


1. The homework is to modify the project that you did as the Exercise 3 above as described below.  (You can modify the dojo-json-solution2 project, that is provided as <LAB_UNZIPPED_DIRECTORY>/ajaxdojowidget/solutions/dojo-json-solution2.) (You can name the new project in any way you want but here I am going to call to call it as mydojofisheye.  Trouble-shooting: When you run mydojofisheye project and the IDE complains that mydojofisheye project already exists, please change the Context Root of the sun-web.xml file, which you find under WEB-INF directory, to mydojofisheye or undeploy mydojofisheye project.)
2. Send the following files to ajaxhomework@sun.com with Subject as AJAXHomework-ajaxdojowidget.