Spring 4 MVC - Building a RESTful Web Service (JSON Response)

By Yashwant Chavan, Views 26017, Date 07-Jan-2017

In this tutorial, You will learn how to Build a RESTful Web Service using spring 4 MVC. RestController accepts HTTP GET request and returns the JSON representation. So let's start from scratch with step by step guide.

tags spring

Spring 4 Eclipse project set up

Spring MVC 4 - Building a RESTful Web Service (JSON Response) - Eclipse project setup

Tools and Technologies

  1. Apache Maven 3.0.4
  2. JDK 1.8
  3. Spring 4.1.4.RELEASE
  4. Jackson API 2.4+

pom.xml

As we are using Maven project. Let's define the spring 4 specific maven dependencies.

<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>com.technicalkeeda</groupId>
    <artifactId>Spring4Examples</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>Spring4Examples</name>
    <description></description>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <spring.version>4.1.4.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</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-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.1</version>
        </dependency>


    </dependencies>
</project>

Spring 4 Application Configuration

@EnableWebMvc annotation is used to enable Spring MVC.

@Configuration annotation imports the Spring configuration. @Configuration objects are managed as Spring beans within the container, imported configurations are used to injected using @Autowired or @Inject.

@ComponentScan is equivalent to <context:component-scan base-package="..." used to lookup the beans and components classes in the spring context.

package com.technicalkeeda.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = "com.technicalkeeda")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

WebApplicationInitializer Configuration

Earlier we used to define web.xml to declare the dispatcher related configurations. Now we are using 100% code base (annotation and java config ) approach to doing the application configuration.

WebApplicationInitializer interface is implemented using Servlet 3.0+ style, Which is used to configure the ServletContext programmatically rather than traditional web.xml-based approach.

package com.technicalkeeda.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfig.class);
        ctx.setServletContext(container);

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

Define RestController (@RestController)

Let's create a simple Controller class PersonController and annotate it with @RestController annotation. The @RestController annotation indicates that a particular class serves the role of a Rest Controller.

Which accept HTTP web-service requests and returns the JSON response. Each method is declared with @RequestMapping annotation which ensures that HTTP request is mapped to respected method implementation. e.g. "/persons" is mapped to persons() method.

Spring uses the Jackson JSON library to automatically marshal instances of type Person into JSON response.

package com.technicalkeeda.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.technicalkeeda.bean.Person;

@RestController
public class PersonController {

    @RequestMapping("/person/{id}")
    public Person person(@PathVariable("id") int personId) {
        for (Person person: getPersons()) {
            if (person.getPersonId() == personId) {
                return person;
            }
        }

        return null;

    }

    @RequestMapping("/persons")
    public List < Person > persons() {
        return getPersons();
    }

    public List < Person > getPersons() {

        List < Person > persons = new ArrayList < Person > ();
        persons.add(new Person(1, "Yashwant", "Chavan", 35));
        persons.add(new Person(2, "Mahesh", "More", 40));
        persons.add(new Person(3, "Ganesh", "Patil", 30));

        return persons;
    }
}

Person Pojo

This is simple Person pojo class which contains different attributes like personId, firstName, lastName and age.

package com.technicalkeeda.bean;

public class Person {

    private int personId;
    private String firstName;
    private String lastName;
    private int age;

    public Person() {

    }

    public Person(int personId, String firstName, String lastName, int age) {
        super();
        this.personId = personId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public int getPersonId() {
        return personId;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

Deploy and Execute

Let’s verify REST APIs. Enter URI (http://localhost:8080/Spring4Examples/person/1) in your browser. It will display JSON response for person id = 1.

Spring MVC 4 - Building a RESTful Web Service (JSON Response) - Find By ID

Display all persons - http://localhost:8080/Spring4Examples/persons

Spring MVC 4 - Building a RESTful Web Service (JSON Response) - Find All Persons
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com