Srikanth Technologies

A RESTFul Web Service in Java and Client in JavaScript

REST (Representational State Transfer) based web services are becoming important with every passing day. They are replacing their predecessors - SOAP based web services. The main reason to build a RESTFul web service is; it's simplicity and usage of pure HTTP protocol, usage of plain text or JSON (JavaScript Object Notation) or XML for data transfer.

Building A RESTFul Web Service

We will first build a simple web service using REST. It is used to get details of employees based on the given employee number. Employee number is passed as query string to the web service, which then sends details of the employee using JSON string. The details include employee name and age. I have actually hardcoded the details of employees to simplify the task. However you can replace this simple code with whatever you want. Only the code in web service will change and the rest remains the same.

The following are the steps to create a simple RESTFul web service using NetBeans 6.5, which has got support for JAX-RS (Java API for XML RESTful Web Services). It uses Jersey, which is RI (Reference Implementation)  for JAX-RS.

We use Tomcat 6.0 as the web container for this.
  1. Start NetBeans IDE 6.5.
  2. Create a new web project by using File->New Project. Select Java Web under Categories and select Web Application under Projects.
  3. Enter the name of the project as restdemo and select Apache Tomcat 6.0 as the web server.
  4. Once a new web application is created, click on the project in Projects window. Click on right button to invoke popup menu. Select New -> Other.
  5. Select Web Services in the Categories and RESTFul web services from Pattern under FileTypes.
  6. Select Singleton as the design pattern.
  7. In the next screen, select the following details.  Path : Employee MIME Type : application/json
  8. Click on Finish to create a RESTFul web service. NetBeans creates a class with the name EmployeeResource, which is associated with annotation @Path("employee"). Modify the code in EmployeeResource as follows.

    package ws;
    
    import javax.ws.rs.core.Context;
    import javax.ws.rs.core.UriInfo;
    import javax.ws.rs.Path;
    import javax.ws.rs.GET;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MultivaluedMap;
    
    @Path("/employee/{empno}")   // make this class processes this url. empno is a variable that represents employee number.
    public class EmployeeResource {
        public EmployeeResource() {
        }
        @GET   // this method process GET request from client
        @Produces("application/json")   // sends JSON
        public String getJson( @PathParam("empno") int empno) {  // empno represents the empno sent from client   
          switch(empno) {
              case 1 :
                  return "{'name':'George Koch', 'age':58}";
              case 2:
                  return "{'name':'Peter Norton', 'age':50}";
              default:
                  return "{'name':'unknown', 'age':-1}";
          } // end of switch
       } // end of getJson()
    } 
    
  9. The following are important entries in web.xml.

       <servlet>
            <servlet-name>ServletAdaptor</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Converter</servlet-name>
            <url-pattern>/Converter</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>ServletAdaptor</servlet-name>
            <url-pattern>/resources/*</url-pattern>
        </servlet-mapping>
       
    
  10. Build and deploy the project.
  11. You can test the service by using the url -> http://localhost:8084/restdemo/resources/employee?empno=1
  12. As it sends JSON string, your browser will prompt you to save it. Save the result and open it with any text editor to see the JSON string.

Creating Client To Consume RESTFul Web Service

Once your web service is hosted, it can be accessed using any client. In this demo we create a client that is a simple HTML page with JavaScript. It takes employee number from user and displays name and age of the employee. It uses XMLHttpRequest object to invoke web service. Of course it uses AJAX as XMLHttpRequest is heart of Ajax.

Create a simple HTML page using any text editor as follows and run it to test it.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script language="javascript">
    var xmlhttp;
    function init() {
       // put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly
       xmlhttp = new XMLHttpRequest();
    }
    function getdetails() {
        var empno = document.getElementById("empno");
        var url = "http://localhost:8084/webservicedemo/resources/employee/" + empno.value;
        xmlhttp.open('GET',url,true);
        xmlhttp.send(null);
        xmlhttp.onreadystatechange = function() {

               var empname =  document.getElementById("empname");
               var age =  document.getElementById("age");
               if (xmlhttp.readyState == 4) {
                  if ( xmlhttp.status == 200) {
                       var det = eval( "(" +  xmlhttp.responseText + ")");
                       if (det.age > 0 ) {
                          empname.value = det.name;
                          age.value = det.age;
                       }
                       else {
                           empname.value = "";
                           age.value ="";
                           alert("Invalid Employee ID");
                       }
                 }
                 else
                       alert("Error ->" + xmlhttp.responseText);
              }
        };
    }
  </script>
  </head>
  <body  onload="init()">
   <h1>Call Employee Service </h1>
   <table>
   <tr>
       <td>Enter Employee ID :  </td>
       <td><input type="text" id="empno" size="10"/>  <input type="button" value="Get Details" onclick="getdetails()"/>
   </tr>
   <tr>
       <td>Enter Name :  </td>
       <td><input type="text" readonly="true" id="empname" size="20"/> </td>
   </tr>

   <tr>
       <td>Employee Age : </td>
       <td><input type="text" readonly="true" id="age" size="10"/> </td>
   </tr>
   </table>
  </body>
</html>

Run the above HTML page by invoking it in browser. Enter employee number 1 or 2 and click on button to get details into textboxes. If you enter any employee number other than 1 or 2 then you will error message saying "Invalid Employee Number".