spring

Spring @RequestBody Annotation Example

Welcome readers, in this tutorial we will show how to implement the Spring @RequestBody Annotation to convert the incoming Json request to a Model object.

1. Introduction

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

1.2 Spring Mvc Framework

Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet

Spring @RequestBody Annotation - Model View Controller (MVC) Overview
Fig. 1: Model View Controller (MVC) Overview

Now, open up the Eclipse IDE and let us see how to implement this tutorial.

2. Spring @RequestBody Annotation Example

Here is a systematic guide for implementing this tutorial in the Spring Mvc framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring @RequestBody Annotation - Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring @RequestBody Annotation - Create a Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Spring @RequestBody Annotation - Project Details
Fig. 4: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring @RequestBody Annotation - Archetype Selection
Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring @RequestBody Annotation - Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

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>com.spring.mvc</groupId>
	<artifactId>SpringRequestBodyAnnotation</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Developers can start adding the dependencies they want like Servlet API, Spring Mvc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring mvc framework. The rest dependencies such as Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:

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>com.spring.mvc</groupId>
	<artifactId>SpringRequestBodyAnnotation</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringRequestBodyAnnotation Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.8.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.6</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringRequestBodyAnnotation</finalName>
	</build>
</project>

3.2 Configuration Files

Let us write all the configuration files involved in this application.

3.2.1 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>SpringRequestBodyAnnotation</display-name>

	<servlet>
		<servlet-name>requestbodydispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>requestbodydispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

3.2.2 Spring Configuration File

To configure the spring framework, developers need to implement a bean configuration file i.e. requestbodydispatcher-servlet.xml which provide an interface between the basic Java class and the outside world. Put this XML file in the SpringRequestBodyAnnotation/src/main/webapp/WEB-INF folder and add the following code to it:

requestbodydispatcher-servlet.xml

<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:annotation-config />

	<!-- for the stereotype annotation to work -->
	<context:component-scan base-package="com.spring.mvc.controller" />
	<context:component-scan base-package="com.spring.mvc.component" />

	<mvc:annotation-driven />
</beans>

3.3 Java Class Creation

Let us write the Java classes involved in this application.

3.3.1 Model Class

This pojo class defines the properties to which the user input will be mapped to. Add the following code to it:

MyMath.java

package com.spring.mvc.component;

import org.springframework.stereotype.Component;

@Component
public class MyMath {

	private int number1;
	private int number2;

	public int getNumber1() {
		return number1;
	}

	public void setNumber1(int number1) {
		this.number1 = number1;
	}

	public int getNumber2() {
		return number2;
	}

	public void setNumber2(int number2) {
		this.number2 = number2;
	}
}

3.3.2 Controller Class

Let us create a simple class where the @RestController annotation specifies this class as a spring controller and is responsible for handling the incoming requests. In here,

  • A method argument is annotated with @RequestBody annotation. This will bind the incoming HTTP request body to that parameter.
    • To deserialize the request body to the domain object spring uses the HTTP message converters to convert the HTTP request body into the domain object

Add the following code to it:

MyMathCtrl.java

package com.spring.mvc.controller;

import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.spring.mvc.component.MyMath;

@RestController
public class MyMathCtrl {

	@RequestMapping(value="/sum", method=RequestMethod.POST)
	public int addition(@RequestBody Map<String, Integer> param) {
		int number1 = param.get("number1");
		int number2 = param.get("number2");
		return number1 + number2;
	}

	@RequestMapping(value="/sum2", method=RequestMethod.POST)
	public int additionPojo(@RequestBody MyMath math) {
		int number1 = math.getNumber1();
		int number2 = math.getNumber2();
		return number1 + number2;
	}
}

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Spring @RequestBody Annotation - Deploy Application on Tomcat
Fig. 8: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

We will test this sample application using a GUI based client. Launch the Postman tool and hit the different URL’s to fetch the data from the database and display the results in the JSON format.

5.1 Addition

The HTTP POST method creates the new resources. Hit the following URL in the Postman tool to pass the resources to the controller method.

http://localhost:8082/SpringRequestBodyAnnotation/sum

Input

{
	"number1": 12,
	"number2": 12
}

These input parameters get mapped to the @RequestBody annotation argument (i.e. Map<String, Integer> param) and produce the output as 12.

5.2 Addition with Pojo

The HTTP POST method creates the new resources. Hit the following URL in the Postman tool to pass the resources to the controller method.

http://localhost:8082/SpringRequestBodyAnnotation/sum2

Input

{
	"number1": 15,
	"number2": 15
}

These input parameters get mapped to the @RequestBody annotation argument (i.e. MyMath math) and produce the output as 30.

Do note, server name (localhost) and port (8082) may vary as per your tomcat configuration. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to implement the @RequestBody annotation in the spring framework. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of the @RequestBody annotation in the Spring framework.

Download
You can download the full source code of this example here: SpringRequestBodyAnnotation

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button