CHAPTER

6

Dojo Toolkit

Chapter Objectives

• Discuss how to use Dojo

• Demonstrate Ajax web application with JSON

6.1 Dojo Toolkit

 

6.1.1 Overview

There are many libraries/frameworks that help Ajax web development and abstract browser differences. The well known of them are the JavaScript-based Dojo Toolkit, Prototype framework, and Direct Web Remoting (DWR) framework; the Yahoo! UI Library (YUI); and the Java based Google Web Toolkit (GWT).

Dojo is a popular open-source, portable DHTML JavaScript toolkit that makes it easier for an Ajax developer to build Ajax requests. Why is Dojo called a toolkit? Dojo not only has a rich collection of libraries for JavaScript and Ajax web development but also provides an extensive, reusable, and customizable widget system supporting user-defined widgets, an enhanced event handling system, and an I/O system that simplifies complicated data transfer between client and server.

Dojo abstracts many of the differences between browsers, so Dojo is portable.

For example, because Dojo's widget system works on top of standard HTML, Dojo developers can add gracefully degradable functionality widgets to their existing web pages without worrying about disabled JavaScript or working with old browsers so that they can still browse the page with the underlying HTML functionality.

Dojo is a cross-browser-oriented tool that supports various web browsers such as IE, Firefox, and Safari and solves Ajax browser incompatibility problems in ordinary JavaScript.

Dojo has a set of powerful JavaScript libraries organized in packages. Dojo 0.4 used to have a layered structure library hierarchy to organize all Dojo functionality in packages. Dojo 0.9 and later versions (currently 1.0) simplify the structure so that most Dojo functions (Dojo widgets, events, I/O, and others) are available in Dojo core base packages; dijit, t, and dojox (Extended Dojo project) work on top of the Dojo core.

One of the advantages of Dojo is that it wraps XMLHttpRequest and makes the request construction and configuration much easier. It frees developers from detailed configuration of Ajax XMLHttpRequest and from parsing and processing the responses back from the server. Another advantage of Dojo is its widget system available in Dojo core and dijit namespace packages. For example, you can easily convert an ordinary HTML form component such as an input textbox into a Dojo-type widget with many new features. For example, the dojoType attribute enriches the JavaScript input box in the following:

images

which will automatically pop up a calendar of the current month and with today's date highlighted on it. When the input box gets focus, the user can select a date and the selected date will be automatically entered in the textbox.

Dojo widgets also provide many more advanced validation and assistance features than JavaScript. For example, the Dojo widget event and event handling is flexible and powerful. Not only widgets but also functions can fire off events, and there may be multiple event handlers for one event source. The complete Dojo reference documentation can be found at http://www.dojotoolkit.org.

Instead of having a formal introduction to Dojo, you will get started with two simple Dojo Ajax request examples here. (One uses the Dojo xhrGet function to get data from the server and partially update the DHTML page without refreshing the whole page just like all Ajax requests do, and the other uses the Dojo xhrPost method to post the DHTML form data to the server and gets responses back from the server to update the client page partially.)

6.1.2 Ajax XMLHttpRequest with Dojo

Now, let us examine a “Hello world” Dojo Ajax example.

Assume that the file data.txt has a text statement, “Welcome to Dojo Ajax!” in it. This web application just downloads the content of this text file, places it in the HTML div tag “put_here” placeholder, and displays it. Assume that the Dojo core package dojo.js library is installed in the dojo directory in the root directory under the webapps directory of a web server such as Apache Tomcat. If you browse this page, “Welcome to Dojo Ajax” will be displayed in the HTML page. There are three other packages in the dojo installation directory: dijit, dojox, and util, as mentioned before.

Here is the HTML file with an xhrGet Ajax request.

images

In this example, three Dojo methods are used.

dojo.xhrGet() is a request method provided in the Dojo core package that facilitates XMLHttpRequest with the GET request method type. dojo.xhrPost is another request type method to make an XMLHttpRequest. Here is the list of Dojo-supported XMLHttpRequest functions; they all take a property object (po) parameter.

images

XMLHttpRequest takes many argument properties. You can pass in a Javascript object that wraps all necessary properties to the xhrGet request, as shown in the example.

Here is the list of common request property arguments:

 

images url: String type; “/path/to/myServer.php”. URL points to server endpoint.

images content: Object type; {name: “value”}. These properties will be serialized as name1=value2 and passed in the request.

images timeout: numeric type. It waits x milliseconds for the response. If this amount of time passes, then the error callback method is invoked.

images form: dojo.byId(“formId”). It extracts form content and sends it to the server.

images handleAs: String type; “text” is default. It can be “json”, “javascript”, “xml”, etc.

images sync: Boolean type; default is false. It indicates whether the request should be synchronous (blocking) or asynchronous.

images headers: Object type specified in {} format. It is used to send additional HTTP headers in the request.

images load: function(response, ioArgs){}. The load function will be called on a successful response.

images error: function(response, ioArgs){}. The error function will be called in case of an error.

images handle: function(response, ioArgs){}. The handle function will be called in case of either success or error.

The dojo.byId(String id) function in the preceding example is used in the same way as document.all.id in IE or document.getElementById(id) in standard DOM. You use this method to locate the “put_here” division/section in this HTML document and to insert the response content in the innerHTML div placeholder of the HTML page.

dojo.addOnLoad(<function>) in the example lets the specified function be invoked as Dojo starts so that the welcome function is called in turn.

The next example shows a Dojo xhrPost Ajax request in the HTML file.

The request is sent to a JSP called response.jsp, which will respond to the Ajax xhrPost form request with a provided user name and say,“Hello <user name>!”.

images

images

In this example you wrap all properties in an object, cl, and pass it to the xhrPost() function. When the user types a username in the input box, the username goes with “myName” object. Once the URL target gets the request, the response.jsp at the server responds to it with a greeting, “Hello <username>”, where <username> is the name that the user typed at the client side.

images

Here the request.getParameter(“myName”) transfers the username user input in the form and assigns it to a variable name and then displays the greeting on the JSP page. In this example, there are two JSP pages; one is used for form input and the other is used for the response page.

6.2 Dojo xhrGet Request with JSON Data

 

In this section you will see how easily the JSON data can be handled in the Dojo xhrGet() Ajax request. Dojo frees web developers from complicated Ajax request configuration and coding tasks such as parsing and converting the JSON data into a JavaScript object. You just need to specify that the response is handled in JSON format. Assume that the ajaxData.txt file on the server has JSON syntax data, as

images

The following Ajax request retrieves a JSON object and puts parsed information into the <div> with an id of ‘json-data’. The xhrGet() function takes the JSON format argument, which includes server url, data format handleAs, and a load function (called back when the response comes back successfully).

images

To recap: these brief examples have given you a basic idea of why people use Dojo and JSON for asynchronous XMLHttpRequest calls.

6.3 Examples and Lab Practice

 

You will practice three hands-on labs in this section. All labs use the Dojo toolkit for Ajax web application: the first shows how to develop an Ajax web application to get data from the server with the Dojo xhrGet() function; the second lab shows how to post form data to the server and ask the server to respond to the request on the form data with the Dojo xhrPost() function; and the last shows how to use JSON data in Ajax web applications with the Dojo toolkit.

Lab 1: Using Dojo xhrGet in Ajax Applications

Installing and adding an external Tomcat server in NetBeans 6.0:

Reference: http://wiki.netbeans.org/AddExternalTomcat

It is assumed that Apache Tomcat NetBeans 6.0 and the latest JDK are installed on your computer. In NetBeans 6.0 we need to add the Tomcat server externally. Let us see the configuration of the Tomcat 6.0 server.

Tomcat 6.0 setup:

You can either install the executable file to install Tomcat 6.0 or you can extract the Tomcat6.0.zip folder to the drive; for example, you can extract it to the drive C:Tomcat6.0.

Now you go into your Tomcat/conf/ folder and open tomcat-users.xml in a text editor and add the username and password in which the manager role is assigned to the user.

Here is how your tomcat-users.xml should look:

images

This will add the username as “admin” and password as “mypassword”. In NetBeans 6.0 we need to specify the username and password.

You will build Ajax and Dojo by using JSP technology, and the work will be done in the NetBeans 6.0 IDE. Once the Tomcat server is installed properly, open the NetBeans 6.0 IDE to add Tomcat as an external server.

Step 1: First choose the Services option, select Server, and right-click the icon to add server.

images

Step 2: Select Tomcat 6.0 to install Tomcat 6.0 server, which is already present on the drive.

images

Step 3: Browse and select the Tomcat installation directory. It should be in the directory C:Tomcat6.0 if you have extracted to that folder. If you have installed the executable file, it should be in the Program files folder in Apache Software Foundation.

images

Step 4: Click Finish.You should now be able to see Tomcat 6.0 under Servers.

images

Note: If you have installed the Tomcat executable file, the two files catalina.bat and setclasspath.bat might be missing in the Tomcatin folder. These two files are needed to start Tomcat server from the NetBean 6.0 IDE. If the two .bat files are missing, you can get them from the URL http://forum.java.sun.com/thread.jspa?threadID=664901&messageID=3893743 and then make these two .bat files available to start the server from NetBeans 6.0.

To install Dojo Toolkit:

You can visit http://dojotoolkit.org to download the latest Dojo Toolkit. The current version is 1.02. The Dojo toolkit is free. After downloading, let us start the NetBeans 6.0 IDE.

Step 1:

At the NetBeans Startup, go to Select File → New Project

images

A new window will be opened, then you select Web and Web Application, and then click Next to continue. In the new dialog box, you name your project and choose a location for it. Press Finish when done.

images

You will see a default page index.jsp; rename it to dojoxhrget.jsp and the directory structure looks like this:

images

Step 2:

After creating a project folder, dojoxhrget, you now unzip the downloaded Dojo toolkit in the web folder created by the NetBeans IDE and name it dojo.

images

Step 3:

Replace the default code with the following.

images

images

After typing the code, you launch the server by clicking Run → Run Main Project. In the new default page you can see a button.

images

You create a new file named Hello.txt in the same folder and copy the following in the text file:

images

Step 4:

After these two files are created, launch the server again by clicking Run → Run Main Project. In the new default page you can see a text field. If you click on the button “Click Me”, the text contained in Hello.txt is displayed.

images

In case you are using Apache Tomcat server to load the page, go to C:Pro-gram FilesApache Software FoundationTomcat 6.0webappsROOT and paste the Dojo toolkit that was downloaded.

images

Run the file by opening a browser and go to http://localhost:8080/dojoxhrGet.jsp.

Lab 2: Using Dojo xhrPost in Ajax Applications

Step 1:

At the NetBeans Startup, go to Select File → New Project.

images

A new window will be opened. Select Web and Web Application and click Next to continue. In the new dialog box, name your project and choose a location for it. Press Finish when done.

images

You will see a default page, index.jsp. Rename it to dojoxhrpost.jsp so that the directory structure looks like this:

images

Step 2:

After creating a project folder, dojoxhrpost, you can unzip the downloaded Dojo toolkit in the web folder created by the NetBeans IDE and name it dojo.

images

Step 3:

Copy the following code to the default page index.jsp.

images

images

In the preceding code you include the dojo.js file and use the tundra theme for a fancy display and use the widgets from the dijit package.

After typing the code, launch the server by clicking Run → Run Main Project. In the new default page you can see a text field.

images

Create a new file named response.jsp in the same folder, and copy the following code to it:

images

images

Step 3:

After the two files are created, launch the server again by clicking Run → Run Main Project. In the new default page you can see a text field.

images

If you enter a name in the text field, the page responds to you automatically.

images

Because of the onkeyup=onclick() code, the page is updated character by character when the user keys in his or her name.

images

In case you are using Apache server to load the page, go to C:Program FilesApache Software FoundationTomcat 6.0webappsROOT and paste the Dojo toolkit that was downloaded.

images

You can browse to http://localhost:8080/xhrpost.jsp to run the application.

Lab 3: Using Dojo and JSON in Ajax Applications with xhrGet

This lab shows how to use Dojo to develop Ajax applications where data is transferred in JSON format. In other words, assume that you create a JSON object on an Apache server's ROOT directory by any technology, which is converted to a string stream to be sent to the client, and then client will eval() it to reconstruct a JSON object to process.

Here is the JSON object about an employee.

images

For example, alert(response.name) will display “John” and alter(response.telephones[0].value) will display 4047230956.

You can develop this Ajax xhrGet application in JSP with the NetBeans toolkit.

Step 1:

At the NetBeans Startup, go to Select File → New Project.

images

After a new window will be opened, you select Web and Web Application, and then click Next to continue.

In the new dialog box, name your project and choose a location for it. Press Finish when done.

images

You will see a default page, index.jsp; rename it to dojojson.jsp and the directory structure will look like this:

images

Step 2:

After creating a project folder, dojojson, you can now unzip the downloaded Dojo toolkit in the web folder created by the NetBeans IDE and name it dojo.

images

Step 3:

Copy the following code to the jsp file.

images

images

Dojo is also available on AOL's Content Delivery Network (CDN). You need to put <src=http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js> instead of installing Dojo on your server.

In this example you used the dijit button and the tundra styles. You can also import it from AOL's CDN by changing the import link to

images

1. The preceding code used the dijit button. To load the module you need to call dojo.require.

images

2. In the HTML page, the button property dojotype should be specified.

images

Dojo has predefined djConfig parameters and applies them as dojo.js is being loaded.

images

Enable parseOnLoad to tell Dojo to apply styles to dijits as it goes through the page during page load.

The file tundra.css is the style sheet for theme tundra. To use the style sheet from tundra, add class=“tundra” to the body tag. After typing the code, launch the server by clicking Run → Run Main Project. In the new default page you can see a button that was created with the dijit and tundra styles.

images

Now create a new file named employer.json in the same folder, and copy the following to this json file, which is actually a text file:

images

You can now launch the server again by clicking Run → Run Main Project. If you click on the button “Click Me”, the text contained in employer.json is displayed.

images

In case you are using Apache Tomcat Server to load the page, go to C:Pro-gram FilesApache Software FoundationTomcat 6.0webappsROOT and paste the Dojo toolkit there.

images

You can run this application by browsing http://localhost:8080/dojoxhrGet.jsp.

6.4 Summary

The Dojo toolkit is a useful and widely used development tool for Ajax and other means of web development. The Dojo-supported package library greatly simplifies JavaScript coding. Specifically, it is much easier to construct an Ajax XMLHttpRequest with Dojo than by using JavaScript only. Also, Dojo supports a powerful widget system that lets developers design their own widgets without worrying about browser incompatibility problems. The JSON standard for transferring data between web clients and servers is also widely accepted by almost all software programming languages and script languages. It reduces the parsing complexity of XML-formatted data. People who are not familiar with the XML DOM API can still easily construct and parse JSON data. This chapter provides readers with hands-on, step-by-step guidelines starting with downloading, moving to configuration to client and server coding, and finally executing. It will help you to practice with real-world development environments and to review all topics learned in this book so far.

6.5 Self-Review Questions

1. JSON is a programming language that supports Ajax requests.

a. True

b. False

2. Dojo is a web server-side programming language.

a. True

b. False

3. dojo.io.bind() is widely used to handle Ajax requests in the current release of Dojo.

a. True

b. False

4. dojo.xhrGet() can post the data in an input form to the web server.

a. True

b. False

5. dojo.xhrPost() can only post data to the server but cannot receive responses from the server.

a. True

b. False

6. Dojo is a JavaScript-based web development open-source toolkit.

a. True

b. False

7. dojo.xhrGet() and dojo.xhrPost() simplify construction of Ajax requests for clients.

a. True

b. False

8. The Dojo toolkit abstracts the browser differences for Ajax requests.

a. True

b. False

9. JSON parsing is much easier than XML parsing.

a. True

b. False

10. Dojo can work with JSON.

a. True

b. False

Keys to the Self-Review Questions

1.b 2.b 3.b 4. b 5. b 6. a 7. a 8. a 9. a 10. a

6.6 Programming Exercises

1. Use the Dojo toolkit to develop a simple web application to retrieve data in a file on a server and partially update the current HTML page.

2. Use the Dojo toolkit to develop a form client to request data on the server on the basis of the client input data in a textbox. One example would be to check a username in the guest book to find out the user information and display it on the client page. If the username is not on the guest book, then alert the user to register.

3. Repeat the “Hello user” example in the lab section, using PHP, JSP, and ASP server pages.

4. Use Dojo widget (with Dojo calendar) and Dojo event to create a simple travel planning application in which the customer can specify the trip source, destination, departure and return dates, and budget. The request is sent to the server for processing.

6.7 References

Introducing JSON, http://www.json.org/.

JSON in JavaScript, http://www.json.org/js.html.

JSON in Java, http://www.json.org/java/index.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset