Sunday, February 18, 2007

Ajax Sandbox (1): Calling Remote Web Services
Play with Json and Java Json API


Json (JavaScript Oject Notation)i s a very interesting format for exchangingdata across domains. Comparing with XML,Jsont is easy to parse with JavaScript,and thus helps to establish a easy way to call remote web services from a Ajaxapplication.

Here is an example of providing web services in Json format by utilizing JavaJson API. There are three core components in this example: a POJO class (Book.java) which stores the data model; a Java servlet (bookWS.java ) which provides web services in Json presentation; A html page (bookWSTest.html) which shows how to call a remote web services in JavaScript using. The working environment is Netbeans 5.5 RC2 as IDE, glassfish v2 as application server.

Data Source

The data source is a POJO class (Book.java),which represents a data table "book" in the database:

id*
title
author
price
1
Java EE 5 Tutorial
John Smith
45.6
2
Ajax For Java Developer
Rayn Todd
29.0

Create a Web Services

The second component is a servlet (bookWS.java) which returns a list of books stored in the database. The result is in Jsonformat and is ready for a client to consume.

Before we go to further, let us take a look at the desired Json format in thisexample:

The following example shows the JSON representation of a object that describe onbook:


List A
:
{"title":"Java EE 5 Tutorial","price":45.6,"author":"John Smith","id":1}

And the returned list of books look like:


List B
:
{"ResultSet":
{"books":
[{"title":"Java EE 5 Tutorial","price":45.6,"author":"John Smith","id":1},
{"title":"Ajax For Java Developer","price":29,"author":"Rayn Todd","id":2}]
}
}

Now let's look at how we can utilize Java Json API to create web service in Json format.

The entity class in accessible via resource injection. A JPQL select query isused to select data from database:


String sql ="select object(o) fromBook as o"; //select all book indb

Query q =em.createQuery(sql); //executequery
ArrayList bookList = newArrayList(q.getResultList()); //store all books in alist
resultSet =getResults(bookList);


A private method is created to convert the list of books into a Json object by utilizing Java Json API:


privateJSONObject getResults(ArrayList bookList){

JSONArray items = new JSONArray();
JSONObject resultSet = newJSONObject();

JSONObject books = new JSONObject();

try {
for (int i = 0; i <bookList.size(); i++){
Book o =(Book)bookList.get(i);

JSONObjectbook_obj = new JSONObject();

book_obj.put("id", o.getId());
book_obj.put("title", o.getTitle());
book_obj.put("author", o.getAuthor());
book_obj.put("price", o.getPrice());
items.put(book_obj);
}

books.put("books", items);
resultSet.put("ResultSet", books);

}catch (JSONException e){
System.out.println("Error: Could not create Book JSONObject");
}
return resultSet;
}


The resulting Json object is then serialized and returned to client:


out.println(callback + "(" +resultSEt.toString() + ")");


"callback" is the name of callback function that can be defined by users' inputand retrieved by:


String callback =request.getParameter("callback");


Don't forget to set up response content type as:


response.setContentType("text/javascript;charset=UTF-8");


We have done all the work in Java servlet. When the servelt receives a request like: http://www.myServer.com/beanTest/bookWS?callback=resultHandler

The returned results should look like:

resultHandler(
	{
"ResultSet":
{
"books":
[
{"title":"Java EE 5 Tutorial","price":45.6,"author":"John Smith","id":1},
{"title":"Ajax For Java Developer","price":29,"author":"Rayn Todd","id":2}
]
}
}
)

Let us go to next section to see how the results is accessible in JavaScript.

Consume Web Services

We use dynamic scripting tag to make a remote web service call. The returned Json object is accessible in the call back function. Here is a sample html page (bookWSTest.html):


<html>

<head>
<title>AjaxRemote Web Services CallTest</title>
</head>
<script>

functionloadPage(){
var url ="http://www.myServer.com/beanTest/booksWS?callback=resultsHandler";
varheadTag =document.getElementsByTagName("head").item(0);
varscriptTag =document.createElement("script");
scriptTag.src = url;
headTag.appendChild( scriptTag );
}

function resultsHandler( resultsObj){
var result =document.getElementById("result");
result.innerHTML= " total number of books is : "+resultsObj.ResultSet.books.length;
}
</script>

<bodyonload="loadPage()">
<divid="result"></div>

</body>

</html>


When page loads, function loadPage() gets executed and write a script tag forthe web services. Inside callback function resultsHandler, the returned Json object is accessible. In this example, the total number of books in db is printed out.



References:

  1. Introducing Json
  2. Json
  3. JSON and the Dynamic Script Tag: Easy, XML-less Web Services for JavaScript
  4. Ajax for Java developers: Java object serialization for Ajax
  5. JSON in Java











2 comments:

Anonymous said...

None of the source links work.

Xiaoyun Tang said...

Thanks. I just figure out what did you mean. I believe I had fixed the links.