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 6.7 - 7.1

Contents

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

Software or Resource Version Required
NetBeans IDE, Java EE bundle 6.7 or later
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.2.x or more recent
Dojo sample project n/a

Notes:

  • You will require an Internet connection to complete several of the steps included in this tutorial.
  • The IDE's Java download bundle enables you to optionally install and register the GlassFish Server Open Source Edition with the IDE. You require a server to simulate client-server communication in this tutorial.
  • It is possible to use a previous version of the IDE for this tutorial. In version 6.5, various toolkits were bundled with the IDE; the core Dojo library, version 1.1.0, is included in NetBeans 6.5. This tutorial requires components from both the Dojo Core library, as well as the Dijit library. You would need to download an updated version of the toolkit (1.2.x or more recent) that contains both Core and Dijit libraries, and register it using the IDE's JavaScript Library Manager.
  • The completed project looks as follows:
    Completed exercise viewed in browser

Adding the Dojo Toolkit to a NetBeans Project

Begin by opening the sample project in the IDE. Once the project is opened, 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. Start NetBeans and click the Open Project button ( Open Project button ) in the IDE's toolbar.
  3. In the Open Project dialog that displays, navigate to the location of the Dojo sample project on your computer and click Open Project.

    When you open the DojoTreeSample project in the IDE, it initially displays in red text with an error badge, indicating 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. Create a folder within the project to contain the Dojo resources you're about to add. To do so, right-click the Web Pages node in the Projects window, and choose New > Folder. In the New Folder dialog, type in 'resources' in the Folder Name field. Note that 'web' is entered by default in the Parent Folder field. Click Finish to create the new folder, and see that it 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'll now see the new resources folder listed under the web directory.
  5. Obtain a copy of the Dojo toolkit (version 1.2.x or more recent). You can download the Dojo toolkit 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 2 components: the ItemFileReadStore module from the Core library, and the Tree widget itself, contained in the Dijit library.
    • dojo.data.ItemFileReadStore: reads the JSON structured contents from an HTTP endpoint (in this tutorial, a servlet) and stores all the items in-memory for simple and quick access.
    • dijit.Tree: The Tree widget that provides a view of the JSON data retrieved from ItemFileReadStore.
  6. To add Dojo resources to your project, simply copy them (Ctrl-C; ⌘-C on Mac) from their location on your computer, then, in the IDE, right-click the new resources node and choose Paste (or simply select the resources node and press (Ctrl-V; ⌘-V on Mac).

    Recall that you only require the Dojo Core and Dijit libraries, so if you've just downloaded a recent copy of the toolkit, note that you do not need to add the DojoX library to your project.

    After you've added the Dojo Core and Dijit libraries, your Projects window should look as follows:
    Projects window displaying Dojo resources

At this stage, you've successfully opened the DojoTreeSample project in the IDE, and have added necessary Dojo resources to the project. In the next step, you'll 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, replace the
    <!-- TODO: link to Dojo resources here -->
    comment with the following <script> tags:
    <script type="text/javascript"
        src="resources/dojo/dojo.js"
        djConfig="parseOnLoad: true">
    </script>
    • djConfig allows you to override global settings that control how Dojo operates (e.g., using the parseOnLoad property).
    • parseOnLoad set to true ensures that widgets and page mark-up are parsed as the page is loaded.
  3. Link to a sample theme contained in the toolkit. Dijit provides three sample themes: tundra, soria and nihilo. These are contained in the dijit/themes folder, which you can verify from the Projects window:
    Dijit theme folders displayed in Projects window
    To link to the nihilo theme, add the following @import statement to the page. You can add it between the page's <head> tags, for example just beneath the <script> tags you just added (changes in bold):
    <script type="text/javascript"
        src="resources/dojo/dojo.js"
        djConfig="parseOnLoad: true">
    </script>
    
    <style type="text/css">
        @import "resources/dijit/themes/nihilo/nihilo.css";
    </style>
  4. Add a class to the page's <body> tag specifying 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

Once you've 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. Replace the
    // TODO: add dojo.require statements here
    comment (line 8) with the following dojo.require statements:
    dojo.require("dojo.data.ItemFileReadStore");
    dojo.require("dijit.Tree");
  2. Add an ItemFileReadStore and Tree widget to the page. Replace the
    <!-- TODO: specify AJAX retrieval -->
    
    <!-- TODO: add Tree widget and configure attributes -->
    comments with the following:
    <div dojoType="dojo.data.ItemFileReadStore"
         url="TribeServlet"
         jsId="indianStore">
    </div>
    
    <div dojoType="dijit.Tree"
         store="indianStore"
         query="{type:'region'}"
         label="North American Indians">
    </div>
    • ItemFileReadStore requires you to specify the url property by pointing to the server-side resource that returns the JSON data. As will be later demonstrated, this is the TribeServlet. You can use the jsId property to give the retrieved JSON data an id, which widgets can then use to refer to the data store.
    • Tree uses the store property to point to the ItemFileReadStore, which provides the JSON data. The query property enables you to arrange the display of data, based on a keyword used in the JSON file.

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 a json.zip file that contains the sources.
  2. Unzip the json.zip file and note that the extracted folder contains the sources listed on http://json.org/java.

    At this point, we want to compile these sources and create a Java archive (JAR file) which we'll be able to add to the DojoTreeSample project.
  3. In the IDE's main toolbar, click the New Project button ( New Project button ).
  4. In the wizard that displays, under Categories select Java, and under Projects select Java Class Library, then click Next.
  5. In the Name and Location panel of the Java Class library wizard, name the new project 'json', then click Finish. The new project is created and opens in the Projects window.

    In the same way that you copied the Dojo toolkit resources and pasted them into the resources folder in the IDE's Projects window, you are going to copy the sources that you just downloaded and paste them directly into the new json project.
  6. Go to the location on your computer where the extracted json.zip file exists and copy (Ctrl-C; ⌘-C on Mac) the json folder. The json folder contains the source files.
  7. In the IDE's Projects window, right-click the <default package> node in the json project and choose Paste.

    When you do this, 'json' becomes the package name, and all sources are listed therein.
    Projects window - sources contained in 'json' project
  8. Build the json project. To do so, right-click the json project node in the Projects window, and choose Clean and Build.

    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 building 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.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.


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 dialog, type in TribeServlet for the class name. Also, have the servlet created in the dojo.indians package.
    New servlet wizard

    Click Next.
  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. Locate the processRequest() method, and change
    response.setContentType("text/html;charset=UTF-8");
    to:
    response.setContentType("application/json");
    This 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 necessary import statements. These are:
    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.

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:

get support for the NetBeans

Support


By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2018, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo