Spring @RequestBody
last modified October 18, 2023
Spring @RequestBody tutorial shows how to bind method parameters to request body with @RequestBody annotation.
Spring is a popular Java application framework for creating enterprise applications.
Spring @RequestBody
@RequestBody annotation binds request body to method parameters.
The process of serialization/deserialization is performed by
HttpMessageConverter. In addition, automatic validation can be
applied by annotating the argument with @Valid.
Spring @RequestBody example
The application binds request body parameters of a form POST and JSON post request to mapped method arguments.
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ ├───bean
│ │ │ User.java
│ │ ├───config
│ │ │ MyWebInitializer.java
│ │ │ WebConfig.java
│ │ └───controller
│ │ MyController.java
│ └───resources
│ logback.xml
└───test
└───java
This is the project structure.
<?xml version="1.0" encoding="UTF-8"?>
<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.zetcode</groupId>
<artifactId>springrequestbodyex</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.49.v20220914</version>
</plugin>
</plugins>
</build>
</project>
We declare the necessary dependencies. The jackson-databind is
needed for serialization in HttpMessageConverter. The application
runs on embedded Jetty; therefore, we declare jetty-maven-plugin.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.springframework" level="ERROR"/>
<logger name="com.zetcode" level="INFO"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
The logback.xml is a configuration file for the Logback logging library.
package com.zetcode.bean;
import java.util.Objects;
public class User {
private String name;
private String occupation;
public User() {
}
public User(String name, String occupation) {
this.name = name;
this.occupation = occupation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) && Objects.equals(occupation, user.occupation);
}
@Override
public int hashCode() {
return Objects.hash(name, occupation);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("name='").append(name).append('\'');
sb.append(", occupation='").append(occupation).append('\'');
sb.append('}');
return sb.toString();
}
}
In the example, we have User bean which has name
and occupation properties.
package com.zetcode.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
MyWebInitializer registers the Spring DispatcherServlet, which
is a front controller for a Spring web application.
package com.zetcode.config;
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.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig implements WebMvcConfigurer {
}
The WebConfig enables Spring MVC annotations with @EnableWebMvc
and configures component scanning for the com.zetcode package.
package com.zetcode.controller;
import com.zetcode.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
@ResponseStatus(value = HttpStatus.OK)
@PostMapping(value="/vals")
public void process(@RequestBody MultiValueMap values) {
logger.info("Values:{}", values);
}
@ResponseStatus(value = HttpStatus.OK)
@PostMapping(value="/user", consumes = MediaType.APPLICATION_JSON_VALUE)
public void process2(@RequestBody User user) {
logger.info("User: {}", user);
}
}
In MyContoller, we have two POST mappings. We use @RequestBody
to bind request parameters to MultiValueMap and User bean.
The bound values are shown in logs.
$ mvn jetty:run
We start the server.
$ curl -i -d "par1=val1&par2=val2" -X POST http://localhost:8080/vals
With the curl tool, we create a reqest to the first mapping.
This creates a form POST data request (content-type is application/x-www-form-urlencoded).
11:57:39.049 INFO com.zetcode.controller.MyController - Values:{par1=[val1], par2=[val2]}
We get this log.
$ curl -i -H "Content-Type: application/json" -d "{\"name\":\"John Doe\",\"occupation\":\"gardener\"}" -X POST "http://localhost:8080/user"
We invoke the second mapping. Here we create a request with JSON data. Note that on Windows we need to escape the double quotes.
12:02:33.817 INFO com.zetcode.controller.MyController - User: User{name='John Doe', occupation='gardener'}
This is the output in the log.
In this article, we have used the @RequestBody annotation to bind
request attributes to method parameters.
Author
List all Spring tutorials.