Create JAX-RS web service using Jersey implementation

 

                            NOTE: Source Code available for download at the bottom of the page

 
What are we going to do?
We will create a simple web application that will output the results based on the url pattern. We will use Jersey implementation to provide the JAX-RS web service capability.
Important JAX-RS annotations:
 
 @Path  The URI path at which the class will be hosted.
 @GET     The annotation will designate the method to process HTTP GET requests.
 @POST     The annotation will designate the method to process HTTP POST method.
 @PUT The annotation will designate the method to process HTTP PUT method. 
 @DELTE The annotation will designate the method to process HTTP DELTE method. 
 @PathParam The URI path parameter is extracted from the request URI and copied into the declared variable.   
 @QueryParam Query parameter is extracted from the request URI and copied into the declared variable.
 @Consumes The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client. 
 @Produces The @Produces annotation is used to specify the MIME media  types of representations a resource can produce and send back to the client: for example, "text/plain"
 
What do you need ?
  • Maven
  • JDK 1.5 or higher
  • eclipse 
  • Jersey- We will be using Jersey implementation in our project. (https://jersey.java.net/)
  • Tomcat
Can we get started ?
 
Step 1:
Create a dynamic web project using maven as shown here.
 
Step 2:
In order to use Jersey implementation for JAX-RS, we will need necessary jars to be downloaded. Add the following dependencies to your pom file and do Maven -> Update Project to get proper references to the jars.
 
pom.xml
													 
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.8</version>
    </dependency>
 
Step 3:
    Our web application has to know how the REST URI's have to be prpcessed. So lets come to an agreement that             JAX-RS calls in our application will follow the following pattern
             http://localhost:8080/JAXRS-Example/rest/.....
 
     We will add the Servlet mapping to forward /rest/* calls to jersey implementation as shown below. In order for         the incoming requests to reach our classes, we will have to make our package visible to Jersey implementation.
     This is done by adding the following.
 
	                <init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.visionjava.restservices</param-value>
</init-param>
 
web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Archetype Created Web Application</display-name>
	<servlet>
		<servlet-name>rest-servlet</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>com.visionjava.restservices</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>rest-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>
 
 
 
Step 4:
    Create RestProcessor class to handle the REST calls. 
											   
package com.visionjava.restservices;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/movies")
public class RestProcessor {
	@GET
	public Response getMsg() { 
		String output = "Movies Rest Service called with GET method:  " ; 
		return Response.status(200).entity(output).build(); 
	}
}
                         URI --> http://localhost:8080/JAXRS-Example/rest/movies
 
    @Path("/movies") designates our RestProcessor class to handle all the incoming URI's with pattern 
        http://localhost:8080/JAXRS-Example/rest/movies  
    @GET designates the getMsg() method to handle all the GET HTTP requests
 
 
@PathParam Example: 
 
        @GET
        @Path("/{param}")
public Response getMsg(@PathParam("param") String msg) { 
    String output = "Service Called with Param  : " + msg; 
return Response.status(200).entity(output).build(); 
        }
                        URi --> http://localhost:8080/JAXRS-Example/rest/movies/inception
 
    @Path("/{param}") designates the method to handles with URi pattern /rest/movies/{parameter-value}
    @PathParam("param") will extract the  parameter-value and initialize variable msg with it.
 
 
@PathParam with subpath example:
	
        @GET    
@Path("/subgenre/{param}")
public Response getMsgThruSubpath(@PathParam("param") String arg ) {
    String output = "Subgenre requested is : " + arg; 
return Response.status(200).entity(output).build(); 
        }
                        URI --> http://localhost:8080/JAXRS-Example/rest/movies/subgenre/horror
 
 
@MatrixParam Example:
	
     @GET
     @Path("/{year}")
     public Response getBookList( @PathParam("year") String year,  @MatrixParam("director") String directorName )  {
        return Response.status(200).entity("Movies for Year + " + year + " with Director " + directorName).build();
     }
                        URI --> http://localhost:8080/JAXRS-Example/rest/movies/2012;director=xyz
                        Output --> Movies for Year + 2012 with Director xyz
 
                                                URI --> http://localhost:8080/JAXRS-Example/rest/movies/2012
                                                                Output --> Movies for Year + 2012 with Director null
 
        Multiple name value pairs can be parsed using MatrixParam. If the value's are not sent as part of URI, the variables     are assigned with default values. 
    
    Care should be taken during type conversions, when type conversion fails the method is not called.
 
That's It !!!
Source Code : JAXRS-Example.rar
Web Analytics