Saturday, December 3, 2011

RESTful: Part 2 - Introduction to RESTful Web Services

Handle the JSON response format with an HTML5 Web client.
In Part 1 of this three-part series, I showed how to quickly create and deploy a Java Platform, Enterprise Edition (Java EE) application that uses Representational State Transfer (REST) Web services with NetBeans.

The application developed in Part 1 will be the basis for this second article on implementing new functionalities.

Now, in Part 2, we will see in detail how to use JavaScript Object Notation (JSON) to handle the response returned to the client.

We will also add a small dose of HTML5, JavaScript, and Ajax to call the Web services, store the information locally, and display the information later.

JSON and HTML5

JSON is a human-readable data format based on JavaScript technology. The structure of JSON is easier to parse and extend than traditional XML. JSON format is used by most applications that provide Web services through Web clients.

HTML5 is the next generation of HTML. It provides new features that are necessary for modern Web applications. It also standardizes many features of commonly available browser technologies that Web developers have been using for years to create rich Web applications without the need for plug-ins.

HTML5 is designed to be cross-platform, and it does not require a specific operating system. The only thing we need is a modern Web browser, such as the latest version of Firefox, Opera, Safari, or Chrome.

We will use the HTML5 storage capabilities to store information on the browser, retrieve it later, and finally display it. This article was tested with Firefox 10.0 and Google Chrome Release 16.0.912.77 m.

HTML5 provides very cool functionalities for storing the data in your browser and accessing the data with JavaScript after the page is loaded.

Lets Code and Test the JSON Representation
To begin, we will modify the resources to ensure that the server returns a response in the format that we want (JSON).

1.    Create the method that will handle the Web services response for the seller:
  1. Select the Source Package node of the AuctionApp project and open the SellerFacadeREST.java file located in the package com.tm.rs.auctionApp.resource.
  2. Remove the XML MIME type (application/xml) from the @Produces annotation of the method get(). The class should now look like Listing 1.
  3. Select the Source Package node of the AuctionApp project and open the  SellerFacadeREST.java file located in the package com.tm.rs.auctionApp.resource.
  4. Remove the XML MIME type (application/xml) from the @Produces annotation of the method get() to handle the JSON response only. The class should now look like Listing 2
  5. Repeat Steps 2, 3, and d for each resource.
Listing 1
@Path("/sellers/")
   @Stateless
        public class SellerFacadeREST {
        @javax.ejb.EJB
        private SellerResource sellerResource;
        @Context
        . . . . 
        @GET
        @Produces({"application/json"})
        public SellersConverter get(@QueryParam("start")@DefaultValue("0")
...
Listing 2
@Stateless
public class SellerFacadeREST {
    @javax.ejb.EJB
    private ItemsResourceSub itemsResourceSub;
    @Context
    @GET
        . . . .
    @Produces({"application/json"})
    public SellerConverter get(@QueryParam("expandLevel")@DefaultValue("1")
    ... 
2.    Test the JSON response format:
  1. Build and deploy the project.
  2. To test the JSON response, open your browser and type the resource URL http://localhost:8080/AuctionApp/resources/sellers/.
 The JSON representation of the resource (Sellers) will be displayed. You can see all the Sellers that you already created in JSON format.

Save the result when prompted by your browser and open the saved file with any text editor to see the JSON string. If you see the result shown in Listing 3, it means your RESTful services are working correctly.

Listing 3
{"@uri":"http://localhost:8080/../../sellers/?#", "seller":
[{"@uri":"http://localhost:8080/../../sellers/1/?#","firstName":"Oddet","id":"1",
"items":{"@uri":"http://localhost:8080/../../sellers/1/items/"},"lastName":"Rossi"},
{"@uri":"http://localhost:8080/../../sellers/2/?#","firstName":"Malonga","id":"2",
"items":{"@uri":"http://localhost:8080/../../sellers/2/items/"},"lastName":"Chrisbel"}]
}
Now that the RESTful Web services are up and running, we are ready to consume them using any client.

Using an HTML5 Client

We need to use a Web client. So we are going to quickly build a sample HTML5 page front end to allow us to perform the following tasks using HTML, JavaScript, and Ajax functionalities:
  • Call the Web services for the Seller.
  • Store the Sellers information on the browser (HTML5 capability). The concept works like the cookies in your browser, but its recommended for larger data.
  • Retrieve the information stored in the browser.
  • Finally, display the information.
JavaScript will be used to invoke the Web service via the XMLHttpRequest object provided by Ajax technology.

1.    Create a sample HTML page:
  1. Right-click the Web Pages node of the AuctionApp project and select New; then select HTML.
  2. Type an HTML filename, such as JsonClient.
  3. Type a folder name, such as jsonUI.
  4. Click Finish.

A new resources HTML file is added to the project.

2.    Edit the created page and modify the HTML <body> tag, as shown in Listing 4.
3.    Add the JavaScript functionality to invoke the Web services and handle the data storage by modifying the HTML <head> tag, as shown in Listing 5.
4.    Retrieve and display the stored information:
  1. Modify the HTML <head> tag as shown in Listing 6.
  2. Save the HTML file.
  3. Build and deploy the project.
Listing 4
<body  onload="init()">
  <h1>Call Seller RESTful Web Service </h1>
  <table>
    <tr>
      <td>Enter Seller ID :</td>
      <td>
         <input type="text" id="sellerid" size="10"/>  
         <input type="button" value="Load seller in local browser" onclick="seveLocal()"/>
      </td>
    </tr>
    <tr> 
      <td colspan="2">-----------------</td>
    </tr>
    <tr>
       <td>Display from local:</td>
       <td>
          <input type="button" value="Read values" onclick="readLocal()"/></td>
    </tr>
    <tr>
       <td>First Name :  </td>
       <td>
          <input type="text" readonly="true" id="firstName" size="20"/> 
       </td>
    </tr>
    <tr>
       <td>Last Name :  </td>
       <td>
          <input type="text" readonly="true" id="lastName" size="20"/>
       </td>
    </tr>
  </table>
</body>

Listing 5
<script language="javascript">
    var xmlhttp;
    function init() {
        xmlhttp = new XMLHttpRequest();
    }

    function seveLocal() { 
      var sellerid = document.getElementById("sellerid"); 
      var url = "http://localhost:8080/AuctionApp/resources/sellers/"+sellerid.value; 
      xmlhttp.open('GET',url,true); 
      xmlhttp.send(null); 
      xmlhttp.onreadystatechange = 
           function() { 
             if (xmlhttp.readyState == 4) { 
               if ( xmlhttp.status == 200) { 
                  var seller = eval( "(" + xmlhttp.responseText + ")"); 
                  if (window.localStorage) {
                    localStorage.setItem("seller",JSON.stringify(seller)); 
                    alert("The data of the seller #" + sellerid.value + has been stored successfully."); 
                  } 
                  else alert("Your Browser does not support LocalStorage.");   
               else alert("Error!!! ->" + xmlhttp.responseText); 
           } 
     };
   }
Listing 6
function readLocal(){ 
   if (window.localStorage) { 
       seller = localStorage.getItem("seller"); 
       seller = JSON.parse(seller); 
       document.getElementById("lastName").value = seller.lastName; 
       document.getElementById("firstName").value = seller.firstName; 
       document.getElementById("sellerid").value = seller.id; 
   }
}
</script>

Testing the HTML Client Application

1.    Call the Web services for seller #2:
  1. Open your browser and type the resource URL http://localhost:8080/AuctionApp/jsonUI/JsonClient.html.
  2. Enter the seller ID (1).
  3. Click Load seller in local browser. A confirmation message is displayed.

2.    Display the stored information:
  1. Retrieve the information for seller #2 from the local storage by clicking Read Values. The first name and last name of seller #2 are displayed.
  2. Now you can smileit works!
Conclusion
We have seen how easy it is to configure RESTful Web services to send a JSON response to the client. The integration of JavaScript and Ajax made it easy to handle and parse the JSON message sent by the Web service.

Finally, HTML5 provides very cool functionalities for storing the data in your browser and accessing the data with JavaScript after the page is loaded. This allows us to save time and bandwidth.

In Part 3 of this series, we will focus on the integration of Java API for XML Web Services (JAX-WS) technology for big Web services.

Reference: Java Magazine 2011 by MAX BONBHEL.

No comments :

Post a Comment