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

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

By Yashwant Chavan, Views 13187, Date 09-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 XML response.

tags spring

Spring 4 Eclipse project set up

Spring MVC 4 - Building a RESTful Web Service (XML 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>

    </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 XML 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.

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;
import com.technicalkeeda.bean.PersonList;

@RestController
public class PersonController {

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

        return null;

    }

    @RequestMapping("/persons")
    public PersonList persons() {
        return getPersonList();
    }

    public PersonList getPersonList() {

        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));

        PersonList personList = new PersonList(persons);
        return personList;
    }
}

Person Pojo

This is simple Person pojo class which contains different attributes like personId, firstName, lastName and age. Mark Person pojo with standard XML annotations like @XmlRootElement and @XmlElement.

package com.technicalkeeda.bean;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "person")
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;
    }
    @XmlElement
    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public String getFirstName() {
        return firstName;
    }
    @XmlElement
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }
    @XmlElement
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

}

PersonList Pojo

This is simple PersonList pojo class which container for person objects.

package com.technicalkeeda.bean;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "persons")
public class PersonList {

    List < Person > persons;

    public PersonList() {
        super();
    }

    public PersonList(List < Person > persons) {
        this.persons = persons;
    }

    public List < Person > getPersons() {
        return persons;
    }

    @XmlElement(name = "person")
    public void setPersons(List < Person > persons) {
        this.persons = persons;
    }

}

Deploy and Execute

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

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

Display all persons in XML format - http://localhost:8080/Spring4Examples/persons

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

Yashwant

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[at][gmail.com]