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.

│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───bean
│   │           │       User.java
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.java
│   │           └───controller
│   │                   MyController.java
│   └───resources
│           logback.xml

This is the project structure.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"













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"?>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
            <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n

        <level value="INFO" />
        <appender-ref ref="consoleAppender" />

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;

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

    public int hashCode() {
        return Objects.hash(name, occupation);

    public String toString() {
        final StringBuilder sb = new StringBuilder("User{");
        sb.append(", occupation='").append(occupation).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;

public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() {
        return null;

    protected Class<?>[] getServletConfigClasses() {

        return new Class[]{WebConfig.class};

    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;

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

public class MyController {

    private static final Logger logger = LoggerFactory.getLogger(MyController.class);

    @ResponseStatus(value = HttpStatus.OK)
    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.


My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Spring tutorials.