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".

Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments


Posted By Christian Louboutin On 10-Jun-10 08:10:52 AM

Great sharing this.



Posted By Zidane07 On 14-Sep-10 02:20:33 PM

This tutorial is a good introduction about JSON via RESTful.

I have tried this code and it works on IE, but my FireBug on FireFox
is indicate that an error is occurred on eval function.



Posted By Rainer Telesko On 27-Mar-11 04:01:12 AM

Hi,

the example looks very fine. However it does not work for me. Do you specify a resource package in Netbeans? Well, I don't know how to specify the resource package.

When I invoke the web page, I get a 404. I use Glassfish instead of Apache, but this should be no problem. I appreciate your help!

Rainer



Posted By mathew On 05-Jun-11 04:12:44 PM

Could you please pass on the steps required to integrate the above example on Eclipse?



Posted By Sasa Jovancic On 10-Jun-11 01:35:22 AM

Excellent post. I faced similar problem to use REST service from javascript, but i worked on creating small client with jquery

http://sasajovancic.blogspot.com/2011/06/javascript-rest-client.html



Posted By gsi On 26-Jul-11 03:29:16 PM

Hi, This is introduction post. But as i have a array of values from JAXB as JSON output. My javascript fail to recognize the output and comes as blank JSON string.
Any help in setting up JAXB or JSON properties
Thanks



Posted By Raja On 10-Aug-11 11:46:00 PM

Excellent posting.



Posted By kirti On 19-Oct-11 12:16:03 PM

thank u sooooo much



Posted By geetha1 On 21-Oct-11 05:47:03 PM

Thanks a lot
the code helped me a lot

can i get code for Post Request instead of get



Posted By Michael On 10-Jan-12 02:50:46 PM

hi, can you give me an server and client example when the client isn't in the same domain (eg. call a rest web service from stand-alone html file)? thanks a lot.. :)



Posted By sana On 13-Mar-12 05:18:54 PM

It's not bad



Posted By Bia On 14-Mar-12 12:44:07 PM

Hi, can you give me an example in which data is fetched from server in jsonArray. thanks..:)



Posted By Moe On 28-May-12 08:36:14 PM

NOT working for me.



Posted By Prem Kumar On 05-Sep-12 10:03:09 AM

Thanks for providing simple and straight forward example to start with REST development. I was able to call the service from java.

Can you provide a sample where we can pass multiple values.



Posted By jarmod On 07-Oct-12 11:50:09 PM

Had to make some changes to get this to work:

@Path("employee")
public class EmployeeResource {
...
@GET
@Path("{empno}")
@Produces("application/json")
public String getJson(@PathParam("empno") int empno) {

and then invoke by:

http://localhost:8084/restdemo/resources/demo/2



Posted By jarmod On 08-Oct-12 12:09:13 AM

I'm guessing that the 'Converter' servlet mapping in your web.xml extract is incorrect.



Posted By vinod On 11-Oct-12 06:43:40 PM

Nice post..



Posted By vinoth On 10-Dec-12 10:10:24 AM

very excellent tutor , very simple. thanks a lot lot

Regards
vino



Posted By Jaime On 10-Feb-13 04:59:11 PM

Instead of using 'xmlhttp' which has cross browser issues, use my jQuery plugin to simplify both usage and REST API definition: https://github.com/jpillora/jquery.rest#basic-usage



Posted By suhas On 30-Apr-13 03:14:10 PM

nice.



Posted By Vikash On 06-May-13 12:40:27 PM

Excellent Demo ........



Posted By vishal On 17-Jun-13 04:51:33 PM

good and very helpful



Posted By Sudha On 06-Sep-13 03:57:55 PM

I want to know how can i use an object,which is returned from GET method in restful service.And Please send me more examples in GET,POST and PUT methods.

Thanks in advance.



Posted By Sahil Bawa On 21-Nov-13 09:19:25 AM

Helped a lot in my final year project! Thanks a lot!
p.s. Your name goes to the reference page. ;)



Posted By Tanaji Bhale On 30-Jan-14 07:42:59 PM

nice explanation....
@ it is simple to call service in javascript rather from servlet ,bcoz in servlet event handling become complicated...



Posted By Neha Lad On 11-Feb-14 12:36:12 PM

Hi This is a good example
Please can you give example for other methods.
Which is very simple in understanding



Posted By TUNISIE On 02-May-14 07:40:58 PM

thnks boss



Posted By dada On 02-May-14 10:25:42 PM

nice work done...we can also look at http://www.morgantechspace.com/2014/04/Call-WebsService-from-JavaScript-with-and-without-jquery.html



Posted By suresh On 01-Apr-15 04:39:03 PM

thank u



Posted By Mallikarjun On 01-Aug-15 08:44:47 AM

Hi.,
Given Good Post,
Will u provide one Example on
Javascript <--> Spring MVC <--> Rest
Thank U



Posted By mani On 28-Dec-16 05:09:52 PM

nice