Spring 3, REST using Jersey 2.6 and Grizzly integration example

In this tutorial I will show you how to integrate REST using Jersey 2.6, Spring 3 and Grizzly web server. So I will use here Grizzly web server so we don’t need to use any other external webserver. I had been googling for many times but I did not get any satisfactory example on REST using Jersey 2.6 with Spring and Grizzly web server. You will get many search results if you search for a REST example using Jersey but you will get most of them are using 1.8. You will also get few results for more than 2.6 like here https://jersey.java.net/documentation/latest/user-guide.html but if you use more than 2.6 then you have to use at least jdk 1.7 but my requirement was to use jdk version 1.6 only. So I decided to write a tutorial on this. So here we go.
Prerequisites

JDK 1.6
Spring 3.x
Jersey 2.6
Junit 4.11
Eclipse 3.6
List of jar files shown in below image
rest jersey 2.6 grizzly spring 3 integration
Create a Dynamic Web Project in Eclipse.
Put the jar files in the lib directory.
We will now look at the source codes.
Spring Service

package in.webtuts.spring.service;
public interface HelloService {
    public void sayHello();
}
package in.webtuts.spring.service;
public class HelloServiceImpl implements HelloService {
    public void sayHello() {
        System.out.println("Hello Service.");
    }
}

 

Spring bean configuration in applicationContext.xml. Put this applicationContext.xml file under src folder.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <context:annotation-config />
    <bean id="helloService" class="in.webtuts.spring.service.HelloServiceImpl" />
</beans>

 
Now create the domain object

package in.webtuts.domain;
public class Book {
    private String title;
    private String author;
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}

 

Create resource class for REST service. Note that how we have injected Spring HelloService in this class.

package in.webtuts.rest.resources;
import java.util.logging.Logger;
import in.webtuts.domain.Book;
import in.webtuts.spring.service.HelloService;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("book")
public class BookResource {
    @Inject
    private HelloService helloService;
    @GET
    @Produces("application/json")
    public Book getBook() {
        //calling spring service
        helloService.sayHello();
        //get new book
        return new Book("Jersey 2.6 REST Spring Grizzly Test", "Soumitra Sarkar");
    }
}

 

Configure the deployment descriptor file to use Jersey for REST API. You will see the applicationContext.xml file is also configured here in the web.xml. This applicationContext.xml file is used for Spring beans configuration.

<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>SpringJerseyREST</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>REST</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>in.webtuts.rest.resources</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Map /rest/* to Jersey -->
    <servlet-mapping>
        <servlet-name>REST</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

 

Now we need to test the service. So I have already said that we don’t need to use any external web server here. So we will see here how we can start and stop the Grizzly server and call the REST service in the java code. Below is the junit test class.

package in.webtuts.rest.test;
import in.webtuts.rest.resources.BookResource;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BookResourceTest {
    private HttpServer httpServer;
    private WebTarget webTarget;
    private static final URI baseUri = URI
            .create("http://localhost:9090/SpringJerseyRest/");
    @Before
    public void setup() throws Exception {
        //create ResourceConfig from Resource class
        ResourceConfig rc = new ResourceConfig(BookResource.class);
        //create the Grizzly server instance
        httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
        //start the server
        httpServer.start();
        //configure client with the base URI path
        Client client = ClientBuilder.newClient();
        webTarget = client.target(baseUri);
    }
    @After
    public void tearDown() throws Exception {
        //if you want to stop the server from the input through keyboard then uncomment below two lines
        // System.out.println(String
        // .format("Application started.%nHit enter to stop it..."));
        // System.in.read();
        //stop the server
        httpServer.shutdown();
    }
    /**
     * Test to get the response.
     */
    @Test
    public void testGetBook() {
        //how we invoke the REST API and get the response using MIME type
        String response1 = webTarget.path("book").request()
                .accept("application/json").get(String.class);
        System.out.println("response1: " + response1);
        //how we invoke the REST API and get the response without using MIME type
        String response2 = webTarget.path("book").request().get(String.class);
        System.out.println("response2: " + response2);
    }
}

 
Now run the above class and see the output.
Output:

Hello Service.
response1: {"author":"Soumitra Sarkar","title":"Jersey 2.6 REST Spring Grizzly Test"}
Hello Service.
response2: {"author":"Soumitra Sarkar","title":"Jersey 2.6 REST Spring Grizzly Test"}

 

Those who want to use maven based web application please have a look at the below pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.webtuts</groupId>
<artifactId>SpringJerseyRest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringJerseyRest Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<jersey.version>2.6</jersey.version>
<spring.version>3.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.grizzly</groupId>
<artifactId>grizzly-http-server</artifactId>
<version>2.3.11</version>
</dependency>
<!-- Jersey Dependencies -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles.repackaged</groupId>
<artifactId>jersey-guava</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-inmemory</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringJerseyRest</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

 
Please feel free to leave a comment if you have any query.

Leave a Reply

Your email address will not be published. Required fields are marked *