RESTEasy 3 + Jackson JSON Integration Example with Tomcat

By Arvind Rai, March 05, 2015
In this page we will learn RESTEasy 3 and Jackson JSON integration example with tomcat. RESTEasy is a REST web service framework provided by JBoss with JAX-RS implementation. To produce JSON response, RESTEasy integrates Jackson API. RESTEasy uses Jackson provider and if we want to use another JSON provider, we have to use @NoJackson annotation. For pretty printing, RESTEasy provides @Formatted annotation. RESTEasy is portable and can run on tomcat and application server. It has rich interceptor model. In web.xml we need to configure RESTEasy HttpServletDispatcher API and context parameter as resteasy.servlet.mapping.prefix for URL mapping. We need to implement application class extending javax.ws.rs.core.Application. Find the complete example to understand RESTEasy how to use. We are using tomcat server for demo. In our example we are creating a REST web service which will respond employee detail as JSON for the given employee id.

Software Required to Run Example

To run our demo, we are using following software and tools.
1. Java 7
2. Eclipse
3. Tomcat 7
4. Gradle

Project Structure in Eclipse

Find the project structure of our demo project in eclipse. This will speed up the learning.
RESTEasy 3 + Jackson  JSON  Integration Example with Tomcat

Gradle to Resolve RESTEasy and Jackson Provider JAR Dependency

Find the Gradle file to resolve JAR dependency for RESTEasy and Jackson provider API.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.jboss.resteasy:resteasy-jaxrs:3.0.10.Final'
    compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.10.Final'
} 

web.xml with HttpServletDispatcher and resteasy.servlet.mapping.prefix

In web.xml, define context parameter and HttpServletDispatcher servlet for RESTEasy.

org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher : RESTEasy dispatcher API to handle request. This is servlet and we need provide a mapping URL for which this servlet accepts URL.
resteasy.servlet.mapping.prefix : RESTEasy provides a context parameter to define prefix URL mapping. It means URL should start with the given prefix.

Find the web.xml.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/employee</param-value>
    </context-param>
    <servlet>
        <servlet-name>RESTEasyService</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.concretepage.EmployeeApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>RESTEasyService</servlet-name>
        <url-pattern>/employee/*</url-pattern>
    </servlet-mapping>
</web-app> 

Create Application Class using javax.ws.rs.core.Application

We have to implement an application that will override a method to return resource that will handle request and response.

javax.ws.rs.core.Application : Application is a JAX-RS abstract class that is implemented to define components. We need to override getSingletons() method to get a set of root resource.

Find the application class which is extending javax.ws.rs.core.Application.
EmployeeApplication.java
package com.concretepage;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class EmployeeApplication extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    public EmployeeApplication() {
        singletons.add(new EmployeeService());
    }
    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
} 
Find the Employee class.
Employee.java
package com.concretepage;
public class Employee {
	private String id;
	private String name;
	private String company;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCompany() {
		return company;
	}
	public void setCompany(String company) {
		this.company = company;
	}
} 

Using @Formatted Annotation for Pretty Print

RESTEasy provides @Formatted annotation which belongs to org.jboss.resteasy.annotations.providers.jackson package using which we get JSON as pretty printing. To use it, annotate the method with @Formatted annotation as below.
@GET
@Path("/prettyprint/{id}")
@Produces("application/json")
@Formatted
public Response employeeDetailPrettyPrint(@PathParam("id") String id) {
	Employee employee = getEmployee(id);
	return Response.ok(employee).build();
}

Create Service Class to handle Request and Response

To develop a service, we have to use JAX-RS API.
javax.ws.rs.Path: Path by which a resource class or method is identified to serve.
javax.ws.rs.PathParam: Binds URI parameter with the variable.
javax.ws.rs.Produces: Media type that is produced by method.
javax.ws.rs.core.Response: Return type of service method that will be used by JAX-RS runtime.

Find the service class used in our REST web service.
EmployeeService.java
package com.concretepage;
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.Response;
import org.jboss.resteasy.annotations.providers.jackson.Formatted;
@Path("/info")
public class EmployeeService {
    @GET
    @Path("/{id}")
    @Produces("application/json")
    public Response employeeDetail(@PathParam("id") String id) {
    	Employee employee = getEmployee(id);
        return Response.ok(employee).build();
    }
    @GET
    @Path("/prettyprint/{id}")
    @Produces("application/json")
    @Formatted
    public Response employeeDetailPrettyPrint(@PathParam("id") String id) {
    	Employee employee = getEmployee(id);
        return Response.ok(employee).build();
    }
    private Employee getEmployee(String id){
    	Employee employee = new Employee();
    	employee.setId(id);
    	employee.setName("Arvind Rai");
    	employee.setCompany("ABC");
    	return employee;
    }
}  

Run and Access RESTEasy Demo Application

Run Gradle file and deploy WAR into tomcat To get response of unformatted JSON, access the URL as given below
http://localhost:8080/concretepage-1/employee/info/34
We will get JSON response. Find the print screen.
RESTEasy 3 + Jackson  JSON  Integration Example with Tomcat
Now to get response as Pretty Print, use the URL as
http://localhost:8080/concretepage-1/employee/info/prettyprint/34
and find the response.
RESTEasy 3 + Jackson  JSON  Integration Example with Tomcat

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us