RESTful Web Service with JSON in Spring Framework

In this tutorial we’ll show you how to create a RESTful web-service that outputs JSON in Spring framework MVC (Java).

Prerequisite


  1. JDK 8
  2. Maven 3
  3. Tomcat v9.0
  4. Jackson 2.x
  5. Spring 4.x

 

 

What is REST?


REST (Representational State Transfer) is a web standards based architecture. A representation of REST does not require the client to know anything about the structure of the representation. Rather, the server needs to provide whatever information the client needs to interact with the service.

  • HTTP Methods and their operations:
  1. POST: Used to create and update entities.
  2. GET: Used to retrieve information. GET requests must be safe and idempotent.
  3. PUT: Same as POST, but the main difference between PUT and POST is that PUT is idempotent.
  4. DELETE: The method is self-exploratory. It simply Removes a resource.

 

 

Creating a new project


First let’s create a new project in eclipse, by fallowing the screen-shots below:

1. Go to File -> New -> Dynamic web application

Dynamic web project

2. Make sure to check “generate web.xml deployment descriptor”

dynamic web project 2

3. Right-click on the project -> configure -> convert to Maven

 

 

Dependencies


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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>RESTExercise</groupId>
 <artifactId>RESTExercise</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <build>
 <sourceDirectory>src</sourceDirectory>
 <plugins>
 <plugin>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>3.5.1</version>
 <configuration>
 <source>1.8</source>
 <target>1.8</target>
 </configuration>
 </plugin>
 <plugin>
 <artifactId>maven-war-plugin</artifactId>
 <version>3.0.0</version>
 <configuration>
 <warSourceDirectory>WebContent</warSourceDirectory>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-dependency-plugin</artifactId>
 <version>2.3</version>
 <executions>
 <execution>
 <phase>package</phase>
 <goals>
 <goal>copy</goal>
 </goals>
 <configuration>
 <artifactItems>
 <artifactItem>
 <groupId>com.github.jsimone</groupId>
 <artifactId>webapp-runner</artifactId>
 <version>8.5.11.2</version>
 <destFileName>webapp-runner.jar</destFileName>
 </artifactItem>
 </artifactItems>
 </configuration>
 </execution>
 </executions>
 </plugin>
 </plugins>
 </build>
 <dependencies>
 <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>4.3.7.RELEASE</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.13</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>4.3.7.RELEASE</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>4.3.7.RELEASE</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.8.1</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.8.1</version>
 </dependency>



 </dependencies>


</project>

 

 

TripDetails Class


A class in which we’ll encapsulate our JSON content:

package com.rest.exercise;

public class TripDetails {
 
 String travelStratDate;
 String travelEndDate;
 String length;
 
 public String getTravelStratDate() {
 return travelStratDate;
 }
 public void setTravelStratDate(String travelStratDate) {
 this.travelStratDate = travelStratDate;
 }
 public String getTravelEndDate() {
 return travelEndDate;
 }
 public void setTravelEndDate(String travelEndDate) {
 this.travelEndDate = travelEndDate;
 }
 public String getLength() {
 return length;
 }
 public void setLength(String length) {
 this.length = length;
 }
 
 
}

 

 

WEB-INF/web.xml


Here we will specify the content of the deployment descriptor element as the fallowing:

<?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>Spring Web MVC Application</display-name>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

 

 

Context Configuration


WEB-INF/mvc-dispatcher-servlet.xml will hold our configuration and enable mvc:annotation-driven:

 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd ">

 <context:component-scan base-package="com.rest.exercise" />

 <mvc:annotation-driven />

</beans>

 

 

RestController


In our JSONController we’ll produce the response and Spring will automatically handle the JSON conversion:

 

package com.rest.exercise;

import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JSONController {

@RequestMapping(value = "/trip/details", method = RequestMethod.GET)
public @ResponseBody List<TripDetails> getJSON() {
List<TripDetails> detailsList = new ArrayList<>();
TripDetails d = new TripDetails();
d.setLength("3");
d.setTravelStratDate("01-01-2016");
d.setTravelEndDate("04-01-2016");
TripDetails d2 = new TripDetails();
d2.setLength("7");
d2.setTravelStratDate("02-02-2016");
d2.setTravelEndDate("09-02-2016");
detailsList.add(d);
detailsList.add(d2);
return detailsList;

}

}

 

 

Expected Results


Finally to check the results go to  http://localhost:8080/RESTExercise/rest/trip/details. If everything work as expected you’ll see the fallowing results:

JSON response

Download or Clone


RESTful download

 

Share

Comments

comments

One thought on “RESTful Web Service with JSON in Spring Framework

Leave a Reply

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