Developing an Ajax Client for RESTful Web Services in NetBeans 7 : Part 3

 

Purpose

This tutorial demonstrates using an Ajax-based HTML page as the client to consume RESTful Web service in NetBeans 7. It provides an overview of two approaches to render AJAX response either in XML or JSON format.

Time to Complete

Approximately 30 minutes.

Overview

Ajax is not a technology, it's a new way of designing user interfaces that has become popular in the last few years. Ajax stands for Asynchronous JavaScript + XML. Ajax supports asynchronous communication to the server. Ajax allows you to render parts of a Web page without having to reload the page completely. An XMLHttpRequest object is used to exchange data with a server behind the scenes.

In this tutorial, you will

The sample application used in this tutorial is used to get details of players based on the given player id. Player id is passed as query string to the web service which then sends details of the player in XML/JSON format. The details include a player's first name, last name and Jersey number.

Prerequisites

Before starting this tutorial, you should have completed Part 1 of this tutorial and met all its prerequisites.The PlayerServer project should be running in NetBeans.

Developing AJAX Client to Consume RESTful Web Services

The following section demonstrates how to create an Ajax-based HTML page which acts as the client to consume RESTful Web service generated by PlayerServer application.

.

Verify PlayerServer application is running as it creates the RESTful Web Services. Otherwise to start the Server, perform the following steps :

a. Open the Projects tab.

b. Right-click PlayerServer project.

c. Select Run.

This action starts the GlassFish server and deploys the application.

On successful deployment of the application - a default jsp page with url, http://localhost:8080/PlayerServer/ is opened in the browser displaying "Hello World".

 

.

To create a HTML file, right-click Playerserver project and select File > New > HTML...


.

Perform the below steps:

a. Enter the following details for

File Name: AjaxRestClient

Folder: You do not have to enter any folder name. The HTML file will be created by default under the Web Pages folder.

b. Click Finish.

AjaxRestClient.html opens in the code editor.

.

In the body section of AjaxRestClient.html add the below code

<table>
<tr>
<td>Enter Player ID : </td>
<td><input type="text" id="playerid" size="10"/>

<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Player Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>

<tr>
<td>Player First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>

<tr>
<td>Player Jersey Number : </td>
<td> <input type="text" id="jerseynumber" size="10"/> </td>
</tr>

</table>

The above code creates the required UI.

.

Right-click AjaxRestClient.html and select Run File.


 

.

Examine the output in the browser.


Rendering RESTful Response in XML Format

The following section demonstrates how to render RESTful Web Service output in XML format in an AJAX based HTML page.

.

Add the below code to create an Ajax request in the head section of the AjaxRestClient.html page.

<script language="javascript" type="text/javascript">
var request = null;

function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}

if (request == null)
alert("Error creating request object!");
}
</script>

 

The createRequest()method is used to create a request object. The request object is ActiveObject for Internet Explorer and XMLHttpRequest object for all other browsers.

.

Add the method getMessage() to the AjaxRestClient.html page.

function getMessage()
{
createRequest();
var playerid = document.getElementById("playerid").value;
id=eval(playerid);
var url = "http://localhost:8080/PlayerServer/resources/com.playerentity.player/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}

In this method we are doing the following :

  • We are initiating a asynchronous request to the server by invoking createRequest() method.
  • Retreiving the player id entered by the user.
  • The url to invoke the RESTful Web Service is http://localhost:8080/PlayerServer/resources/com.playerentity.player/ and the playerid entered by the user is appended to the URL to retrieve details of that particular player.

.

Add the method handleResponse() to the AjaxRestClient.html page.

function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var fnames = xmlDocument.getElementsByTagName("firstname");
var lnames = xmlDocument.getElementsByTagName("lastname");
var jerseynos = xmlDocument.getElementsByTagName("jerseynumber");

for(var i=0; i<fnames.length; i++) {
var fname = fnames[i].childNodes[0].nodeValue;
var lname = lnames[i].childNodes[0].nodeValue;
var jerseyno= jerseynos[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=fname;
document.getElementById('firstname').value=lname;
document.getElementById('jerseynumber').value=jerseyno;
}
}

}


 

This method is invoked to handle the response from the server. The method handleResponse() parses the XML document and assigns the retrieved values to the HTML text boxes.

.

Right-click AjaxRestClient.html and select Run File.

.

Verify the output. Complete the following steps:

a. Enter player id equals to 3.

b. Click GetDetails.


As part of event handling of this button it invokes the getMessage() method which initiates a AJAX request as explained above.

The details of the Player with player id 3 is retrieved and displayed in the HTML page.

 

.

Examine the XML response. Perform the below steps:

a. Enter the this URL, http://localhost:8080/PlayerServer/resources/com.playerentity.player/3 in the browser.

b. The details of player with id 3 is displayed in the browser in XML format.

 

Rendering RESTful Response in JSON Format

 

The following section demonstrates how to render RESTful Web Service output in JSON format in an AJAX based HTML l page..

.

Complete the following steps:

a. Select PlayerServer project and expand RESTful Web Services folder.


b. Right-click PlayerFacadeREST[com.playerentity.player] and select open.


PlayerFacadeREST.java opens in the code editor.

.

Examine the @GET annotation which is invoked when a HTTP GET request is sent to the resource with the desired MIME type. The methods produce response in both XML and JSON formats. However since you want the response to be in JSON format only, you need to modify the @produces annotation.


.

Modify the @produces annotation remove the string "application/xml" , to indicate that this methods produce response in JSON format for HTTP GET requests.



.

Select PlayerServer project in the projects pane. Next right-click and select Clean and Build.


 

.

Right-click PlayerServer project and select Deploy.


.

Perform the following steps:

a. In the projects pane, select PlayerServer project.

b. Right-click and select open, AjaxRestClient.html opens in the code editor.


.

Modify the handleResponse() method to handle JSON response.

function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var det=eval("("+request.responseText+")");
document.getElementById('lastname').value=det.firstname;
document.getElementById('firstname').value=det.lastname;
document.getElementById('jerseynumber').value=det.jerseynumber;

}
}


.

Right-click AjaxRestClient.html and select Run File.

.

Verify the output. Complete the following steps:

a. Enter player id equals to 3.

b. Click GetDetails.

The details of the Player with player id 3 is retrieved and displayed in the HTML page.

.

.

Examine the JSON response. Perform the below steps:

a. Enter the this URL, http://localhost:8080/PlayerServer/resources/com.playerentity.player/3 in the browser.

b. Download and save the response (because currently no client initiated the Request as we just used the browser only).

c. Open the response in Notepad, the details of player with id, '3' is returned in JSON format :

Summary

This tutorial demonstrates using an Ajax-based HTML page as the client to consume RESTful Web service in NetBeans 7. It provides an overview of two approaches to render AJAX response either in XML or JSON format

Comparison of Rendering AJAX Response : XML or JSON format

XML format :

Advantage : The most important advantage of XML is that it's the most easily readable format

Disadvantage: The JavaScript required to insert the data into the HTML page is quite verbose.

JSON format :

Advantage :

Disadvantage:

The format is hard for humans to read and every single comma, quote and bracket should be in the correct place. It is difficult to debug.


Resources

Credits

Hardware and Software Engineered to Work Together Copyright 2011, Oracle and/or its affiliates. All rights reserved