Connecting a Dojo Tree to an ArrayList using JSON

Web 2.0 features are becoming increasingly predominant in web applications. Many web applications now use JavaScript toolkits such as Dojo, which allow web pages to behave more like desktop interfaces while overcoming browser incompatibilities and utilizing code that is maintainable, accessible, and standards-compliant.

This tutorial has been adapted from the Java One Hands-On Lab: Leveraging JavaScript Toolkits for End-to-End Connectivity in Web Applications, and demonstrates how to add and configure a Dojo Tree widget in a web page and enable the server-side to respond to Tree requests in JSON format. In doing so, you will utilize a set of freely available Java classes from http://json.org to process data from an ArrayList into JSON format.

Content on this page applies to NetBeans IDE 7.2 and 7.3

Contents

To complete this document, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE 7.2, 7.3, Java EE
Java Development Kit (JDK) 6 or 7
GlassFish server
or
Tomcat servlet container
Open Source Edition 3.1.x
 
6.x or 7.x
Dojo Toolkit version 1.8.x
Dojo sample project n/a

Notes:


Adding the Dojo Toolkit to a NetBeans Project

Begin by opening the sample project in the IDE. When the project is open, perform the following steps to copy the Dojo resources directly into your project in the IDE's Projects window.

  1. Download the tutorial's Dojo sample project to a location on your computer.
  2. Click the Open Project button ( Open Project button ) in the IDE toolbar to open the Open Project dialog box.
  3. In the Open Project dialog, locate the Dojo sample project on your computer and click Open Project.

    When you open the DojoTreeSample project in the IDE you will see that the project is badged with an error badge to indicate that a reference problem exists.

    Projects window displaying DojoTreeSample project in red text and with error badge

    The reference problem exists because the Java classes used in the project (Tribe, and TribeDataManager) reference classes found in the JSON JAR file, which you will later add in the section Adding the JSON JAR Files to the Project.

  4. Right-click the Web Pages node in the Projects window and choose New > Folder to create a folder to contain the Dojo resources that you are about to add.
  5. Type resources in the Folder Name field in the New Folder wizard.

    Note that 'web' is entered by default in the Parent Folder field.

  6. Click Finish to create the new folder.

    You can see that the new folder is now listed under the Web Pages node in the Projects window.

    Note: The Projects window (Ctrl-1; ⌘-1 on Mac) provides a logical view of important project contents, and is the main entry point to your project sources. The Files window (Ctrl-2; ⌘-2 on Mac) shows a directory-based view of your projects, and includes any files and folders that are not displayed in the Projects Window. In the New Folder dialog in this step, 'web' is entered by default in the Parent Folder field when creating a new item from the Web Pages node. If you open the Files window, you will now see the new resources folder listed under the web directory.

  7. Download a copy of the Dojo toolkit (version 1.8.x or more recent) to your computer from http://www.dojotoolkit.org/downloads.

    Note that the current version of the Dojo toolkit includes the Dojo core, Dijit, and DojoX libraries. In order to implement Dojo's Tree widget, you essentially require two components: the ItemFileReadStore module from the core library and the Tree widget itself contained in the Dijit library.

  8. Extract the Dojo toolkit archive that you downloaded and copy the dojo and dojit folders to your project into the resources folder.

    You can copy them to your project by locating the folders on your local system and simply copying them (Ctrl-C; ⌘-C on Mac) from their location on your computer and then right-clicking the new resources node in the Projects window in the IDE and choosing Paste in the popup menu (or simply select the resources node and press (Ctrl-V; ⌘-V on Mac).

    Note. You do not need to add the DojoX library to your project.

    After you add the Dojo and Dijit libraries, your Projects window should look similar to the following image.

    Projects window displaying Dojo resources

At this stage, you have successfully opened the DojoTreeSample project in the IDE, and have added necessary Dojo resources to the project. In the next step, you will begin working in the HTML file that will display the Tree widget to the end user.

Linking to the Toolkit Resources from a Project File

In order to use resources from the toolkit, you need to link to the dojo.js file, found in the core library. The dojo.js file is the source loader for Dojo and determines the correct host environment to use. While doing so, you can also configure djConfig by adding the parseOnLoad parameter.

  1. In the Projects window, double-click the dojoDemo.html file to open it in the editor.
  2. In the dojoDemo.html file, add the following <script> tags (in bold) between the <head> tags.
    <!-- TODO: link to Dojo resources here -->
    
    <script type="text/javascript">
        var djConfig = {parseOnLoad: true,
            isDebug: true};
    </script> 
    <script
        type="text/javascript"
        src="resources/dojo/dojo.js">
    </script>
        
    </head>
  3. Add a link to the nihilo sample theme contained in the toolkit by adding the following @import statement (in bold) between the <head> tags and beneath the <script> tags that you added.
    <script type="text/javascript">
        var djConfig = {parseOnLoad: true,
            isDebug: true};
    </script> 
    <script
        type="text/javascript"
        src="resources/dojo/dojo.js">
    </script>
    
    <style type="text/css">
        @import "resources/dijit/themes/nihilo/nihilo.css";
    </style>

    The nihilo theme is included by default in the toolkit. You can expand the dijit/themes folder in the Projects window to see other sample themes that are provided by default.

  4. Add the following class selector to the <body> tag of the page to specify the name of the theme you are using. When you do this, any Dojo widget which has been loaded into the page will be rendered using the styles associated with the theme.
    <body class="nihilo">

At this stage, the dojoDemo.html file is ready to accept any code that references the Dojo core and Dijit libraries, and will render any widgets using Dojo's nihilo theme.

Adding and Configuring the Dojo Tree Widget

After you have linked to dojo.js, you can begin adding code to utilize Dojo's modules and widgets. First add code to load the dijit.Tree widget and dojo.data.ItemFileReadStore using dojo.require statements. Then, add the widget and module themselves to the page.

  1. Add the following dojo.require statements (in bold) to the file between the <body< tags.
    <script type="text/javascript">
    
        // TODO: add dojo.require statements here
        dojo.require("dojo.data.ItemFileReadStore");
        dojo.require("dijit.Tree");
    
    </script>
  2. Add the following code (in bold) to add an ItemFileReadStore and Tree widget.
    <!-- TODO: specify AJAX retrieval -->
    
    <!-- TODO: add Tree widget and configure attributes -->
    <div dojoType="dojo.data.ItemFileReadStore"
         url="TribeServlet"
         jsId="indianStore">
    </div>
    
    <div dojoType="dijit.Tree"
         store="indianStore"
         query="{type:'region'}"
         label="North American Indians">
    </div>

    Note. You can ignore the warnings that appear in the editor after adding this code.

At this stage, your dojoDemo.html file is complete, and all client-side modifications to the project are in place. In the following two steps, you'll make changes that affect the project's server-side behavior when Tree requests are made.


Adding Third-Party JSON Conversion Sources as a JAR File to the Project

In this tutorial, the logic that extracts the ArrayList sample data has been prepared for you in the Tribe and TribeDataManager classes. Essentially, it is only necessary to include the third-party Java classes that handle JSON conversion to the project, then add import statements for these classes in the Tribe and TribeDataManager classes. To accomplish this however, you need to first compile the third-party Java classes and create a Java Archive (JAR file). The IDE can help you do this using the Java Class Library wizard.

  1. Visit http://json.org/java and note that Java classes for JSON conversion are freely available. Click the 'Free source code is available' link to download the JSON-java-master.zip file that contains the sources.
  2. Unzip the JSON-java-master.zip file and note that the extracted folder contains the sources listed on http://json.org/java.

    At this point, you want to compile these sources and create a Java archive (JAR file) which you will add to the DojoTreeSample project.

  3. Click the New Project button ( New Project button ) in the toolbar to open the New Project wizard.
  4. In the New Project wizard, select the Java Class Library project template in the Java category. Click Next.
  5. In the Name and Location panel of the Java Class Library wizard, type json as the Project Name. Click Finish.

    When you click Finish the new project is created and opens in the Projects window.

    You now need to copy the JSON sources that you download to the json project in the same way that you copied the Dojo toolkit resources to the DojoTreeSample project.

  6. Extract the JSON-java-master.zip archive and copy (Ctrl-C; ⌘-C on Mac) the json folder that contains the source files.
  7. In the IDE's Projects window, right-click the <default package> node in the json project and choose Paste in the popup menu.

    When you do this, 'json' becomes the package name, and you can expand the package to view the json sources.

    Projects window - sources contained in 'json' project
  8. Right-click the json project node in the Projects window and choose Clean and Build to build the project.

    When you build your project, all Java classes get compiled into .class files. The IDE creates a build folder to contain compiled classes, as well as a dist folder that contains a JAR file for the project. These folders can be viewed from the IDE's Files window.

    After you build the json project, open the Files window (Ctrl-2; ⌘-2 on Mac) and expand the json folder. The build folder contains the compiled sources from the JSON-java-master.zip file and the dist folder contains the JAR file which the DojoTreeSample project needs to reference.

    Files window - compiled sources shown in 'build' folder
    Now that you have the json.jar file, you can resolve the reference problems that the DojoTreeSample project has been exhibiting since you opened it.
  9. In the Projects window, right-click the DojoTreeSample's Libraries node and choose Add JAR/Folder. Then, in the dialog, navigate to the location of the json project's dist folder and select the json.jar file.

    When you exit the dialog, the json.jar file is listed under the project's Libraries node.
    Projects window - JAR file added to Libraries node
    Note: Although the json.jar file is listed under the project's Libraries node, it is referenced from its original location - not copied and added to the project (e.g., you won't be able to locate it under the DojoTreeSample project in the Files window). Therefore, if you change the location of the JAR file, the reference will be broken.
  10. Expand the Source Packages > dojo.indians package and double-click the Tribe and TribeDataManager classes to open them in the editor.
  11. Add necessary import statements to both classes. In each class, right-click in the editor and choose Fix Imports.

    The Tribe class requires the following imports:
    import dojo.org.json.JSONException;
    import dojo.org.json.JSONObject;
    The TribeDataManager class requires the following imports:
    import dojo.org.json.JSONArray;
    import dojo.org.json.JSONException;
    import dojo.org.json.JSONObject;

    Note that the APIs for JSON classes are also provided at http://json.org/java - you may want to keep this page open as you later examine code in Tribe and TribeDataManager.

  12. Examine the ArrayList in TribeDataManager. The ArrayList is a collection of Tribe objects. Looking at the first element of the ArrayList, you can see a new Tribe object created and added to the list:
    indians.add(new Tribe("Eskimo-Aleut", "Arctic", "Alaska Natives"));
    Each Tribe object captures three points of information: tribe, category, and region. The data for this exercise has been taken from Wikipedia's entry on Native Americans in the United States. As you can determine, multiple tribes are classified within a category, and numerous categories may be contained within a larger region.
  13. Open the Tribe class in the editor, and note that it is basically a JavaBean, with the exception of the toJSONObject() method:
    public JSONObject toJSONObject() throws JSONException {
        JSONObject jo = new JSONObject();
        jo.put("name", this.name);
        jo.put("type", "tribe");
    
        return jo;
    }
  14. Switch back to TribeDataManager (Ctrl-Tab) and examine the methods included in the class. Open the Navigator (Ctrl-7; ⌘-7 on Mac) to view a list of fields and properties contained in the class.
    TribeDataManager class viewed in the Navigator
    The most significant method contained therein is getIndiansAsJSONObject(). This method scans the ArrayList, processes the data, and returns it in the form of a JSONObject. The String form of the JSONObject is what is required by Dojo's ItemFileReadStore.
    public static JSONObject getIndiansAsJSONObject() throws JSONException {
    
        JSONObject jo = new JSONObject();
        JSONArray itemsArray = new JSONArray();
    
        jo.put("identifier", "name");
        jo.put("label", "name");
    
        // add regions
        addRegionsToJSONArray(itemsArray);
    
        // add categories
        addCategoriesToJSONArray(itemsArray);
    
        // add tribes
        addTribesToJSONArray(itemsArray);
    
        jo.put("items", itemsArray);
        return jo;
    }
  15. Open the Javadoc on the getIndiansAsJSONObject() method. You can do this by returning to the Navigator (Ctrl-7; ⌘-7 on Mac) and hovering over the method. Otherwise, choose Window > Other > Javadoc from the main menu, then click on the method signature in the editor.
    Javadoc window opened to TribeDataManager class
  16. Examine the example of JSON data that is provided in the Javadoc. Note that the format of the data conforms to the examples provided in the Dojo documentation.

NetBeans IDE's Java Debugger

You will implement a servlet that calls the getIndiansAsJSONObject() method in the next step. Once you do this, you can perform the following steps to use the IDE's Java debugger to step through the method and examine how the JSONObject is formed.

  1. Set a breakpoint on the method (click the line number (i.e., line 99) in the left margin of the editor).
    Method breakpoint set in the editor
  2. Select the DojoTreeSample project in the Projects window.
  3. Run the debugger (click the Debug Project button ( Debug Project button ) in the toolbar).
  4. Use the Step Into ( Step Into button ) and Step Over ( Step Over button ) buttons in the toolbar.
  5. Examine variable and expression values in the Local Variables window (Window > Debugging > Variables).

For more information on the Java Debugger, see the following screencasts:


Within this step, you've compiled third-party sources from http://json.org and added them as a JAR file to the DojoTreeSample project. You then added import statements to classes from the JAR file in the Tribe and TribeDataManager classes. Finally, you examined some of the methods contained in TribeDataManager which are used to convert the ArrayList data into a JSON string.

In the next step, you'll create a servlet which will handle incoming requests by calling the TribeDataManager's getIndiansAsJSONObject() method, and send the resulting JSON string a response to the client.


Preparing a Servlet to Initiate a JSON Response

Recall that you specified 'TribeServlet' as the value for the url property when adding the ItemFileReadStore to your web page. This is the destination on the server-side that is tasked with preparing and returning the JSON data to the client. Let's now create this servlet.

  1. In the Projects window, right-click the dojo.indians source package and choose New > Servlet.
  2. In the New Servlet wizard, type TribeServlet for the class name. Confirm that dojo.indians is specified as the package. Click Next.
    New servlet wizard
  3. Note that in the wizard's Configure Servlet Deployment step, the 'Add information to deployment descriptor' option is selected by default, meaning that the default servlet name and URL pattern will automatically be added to web.xml. Consequently, any requests to the host domain (i.e., http://localhost:8080/DojoTreeSample/) for TribeServlet will be handled by the dojo.indians.TribeServlet class.
  4. Click Finish. A skeleton class for the new servlet is generated and opens in the editor.

    The function of the servlet is to call the getIndiansAsJSONObject() method, and use the data from this method to respond to the client request. In order to prepare a response in JSON format, we have to first set the mime type of the response to JSON format.

  5. Modify the processRequest() method by making the following changes (in bold).
    response.setContentType("application/json");

    This change sets the Content-Type header of the HTTP Response to indicate that any returned content is in JSON format.

  6. Replace the commented code within the processRequest() method's try block with the following (changes in bold):
    try {
    
        JSONObject jo = null;
        try {
            jo = TribeDataManager.getIndiansAsJSONObject();
        } catch (JSONException ex) {
            System.out.println("Unable to get JSONObject: " + ex.getMessage());
        }
    
        out.println(jo);
    
    } finally {
        out.close();
    }

    To reformat your code, right-click within the editor and choose Format.

  7. Use the IDE's hints to add the following import statements.
    import dojo.org.json.JSONException;
    import dojo.org.json.JSONObject;
  8. To run the project, select the DojoTreeSample project node in the Projects window, then click the Run Project ( Run Main Project button ) button in the IDE's toolbar.

    The browser opens to display the welcome page (dojoDemo.html), and you can see that the Dojo Tree widget is displaying data from the ArrayList properly, as in the screenshot above.
Send Us Your Feedback

See Also

For more information about Dojo, refer to the official documentation:

For more information about JavaScript and JavaScript toolkit features on netbeans.org, see the following resources: