Thursday, April 4, 2013

Create RESTful web services in java(JAX-RS) using jersey

In this post,we will develop RESTful web service using jersey in eclipse

Web service Tutorial Content:

Part-1:Introduction to web services
Part-2:SOAP web service introduction 
Part-3:RESTful web service introduction
Part-4:SOAP web service example in java using eclipse
Part-5:JAX-WS web service eclipse tutorial
Part-6:JAX-WS web service deployment on tomcat 
Part-7:Create RESTful web service in java(JAX-RS) using jersey

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

Jersey is the reference implementation for this specification. Jersey contains basically a REST server and a REST client. The core client can communicate with the server using jersey lib.

On the server side Jersey uses a servlet which scans predefined classes to identify RESTful resources. Via the web.xml configuration file for your web application.

The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 
This servlet analyzes the incoming HTTP request and selects the correct class and method depending on  request. This selection is based on annotations provided in the class and methods. 

Prerequisites:


1) Open eclipse.
2) Create new dynamic web project named "RESTfulWebserviceExample"

3) Now go to location where you have download jersey and go to jersey-archive-1.17->lib
folder.you can have all jars but for now you can copy following jars
  • asm-3.1
  • jersey-client-1.17
  • jersey-core-1.17
  • jersey-server-1.17
  • jersey-servlet-1.17
  • jsr311-api-1.1.1
Paste all above copied jars to WebContent->WEB-INF->lib

Add all these jars to eclipse build path.
Right click on project(RESTfulWebserviceExample)->properties


Click on Java Build Path and then Add jars as shown in above diagram.

go to project->WebContent->WEB-INF->lib and select all jars then click on ok.

Click ok.Jersey jars added to class path.
4) Create new package named "org.arpit.javapostsforlearning.webservice"

5)Create  FeetToInchAndInchToFeetConversionService.java

package org.arpit.javapostsforlearning.webservice;
/**
* @author Arpit Mandliya
*/

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
@GET
@Path("/InchToFeet/{i}")
@Produces(MediaType.TEXT_XML)
public String convertInchToFeet(@PathParam("i") int i) {

int inch=i;
double feet = 0;
feet =(double) inch/12;

return "<InchToFeetService>"
+ "<Inch>" + inch + "</Inch>"
+ "<Feet>" + feet + "</Feet>"
+ "</InchToFeetService>";
}

@Path("/FeetToInch/{f}")
@GET
@Produces(MediaType.TEXT_XML)
public String convertFeetToInch(@PathParam("f") int f) {
int inch=0;
int feet = f;
inch = 12*feet;

return "<FeetToInchService>"
+ "<Feet>" + feet + "</Feet>"
+ "<Inch>" + inch + "</Inch>"
+ "</FeetToInchService>";
}
}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/XML") is produced.

@PathParam: Used to inject values from the URL into a method parameter.This way you inject inch in convertFeetToInch method and convert that to feet.
6)Now you need to create web.xml and put it under /RESTfulWebserviceExample/WebContent/WEB-INF/
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RESTfulWebServiceExample</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.arpit.javapostsforlearning.webservices</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
In above <param-value>,put your web service package.
8) Run project:right click on project->run as ->run on server
9) Test your REST service under: "http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2". 

You will get output as :

If You see web service information page then you are done.

Creating a Restful Web Service Client:

Create ConversionServiceClient.java under org.arpit.javapostsforlearning.websevices.client

package org.arpit.javapostsforlearning.webservices.client;

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class ConversionServiceClient {
    static final String REST_URI = "http://localhost:8080/RESTfulWebServiceExample";
    static final String INCH_TO_FEET = "/ConversionService/InchToFeet/";
    static final String FEET_TO_INCH = "/ConversionService/FeetToInch/";

    public static void main(String[] args) {

        int inch=12;
        int feet=2;

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(REST_URI);

        WebResource addService = service.path("rest").path(INCH_TO_FEET+inch);
        System.out.println("INCH_TO_FEET Response: " + getResponse(addService));
        System.out.println("INCH_TO_FEET Output as XML: " + getOutputAsXML(addService));
        System.out.println("---------------------------------------------------");

        WebResource subService = service.path("rest").path(FEET_TO_INCH+feet);
        System.out.println("FEET_TO_INCH Response: " + getResponse(subService));
        System.out.println("FEET_TO_INCH Output as XML: " + getOutputAsXML(subService));
        System.out.println("---------------------------------------------------");

    }

    private static String getResponse(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();
    }

    private static String getOutputAsXML(WebResource service) {
        return service.accept(MediaType.TEXT_XML).get(String.class);
    }
}

Run above program
Output:
INCH_TO_FEET Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/InchToFeet/12 returned a response status of 200 OK
INCH_TO_FEET Output as XML: <InchToFeetService><Inch>12</Inch><Feet>1.0</Feet></InchToFeetService>
---------------------------------------------------
FEET_TO_INCH Response: GET http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2 returned a response status of 200 OK
FEET_TO_INCH Output as XML: <FeetToInchService><Feet>2</Feet><Inch>24</Inch></FeetToInchService>
---------------------------------------------------
Source:Download 

No comments:

Post a Comment