Spring @ResponseBody Annotation Example

In this section we will learn about @ResponseBody Annotation. 


@ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.

The @ResponseBody annotation is used at method level or method return type level. 

The @ResponseBody constructs the response body as JSON or XML or other media type based on following points. 

1. MessageConverter configured in the application. 

2. Media-type configured by produces attribute in annotations @RequestMapping, @GetMapping etc. 

3. Media-type configured by accept request header. 

The @ResponseBody only configures body of response. To set response status code we use @ResponseStatus annotation at method level. If status code is not set explicitly, default status code is set to response. The @ResponseBody is used with @Controller annotation, the @ResponseBody is annotated at method level whereas @Controller is annotated at class level. If we use @RestController annotation, then @ResponseBody is not needed to use. This is because 

@RestController = @Controller + @ResponseBody

    Using @ResponseBody

    The @ResponseBody can be used at method level as well as method return type level. 

    1. Find the code to use @ResponseBody at method level.

    @GetMapping(value = "user")
    @ResponseBody
    public List<User> getUsers() {
       List<User> list = userService.getAllUsers();
       return list;
    } 


    2. Find the code to use @ResponseBody at method return type level.

    @GetMapping(value = "user")
    public @ResponseBody List<User> getUsers() {
       ------
    } 


    3. To produce JSON response body, we need to use produces attribute of @GetMapping and assign it application/json. Find the code that will produce JSON response body.

    @GetMapping(value = "user",  produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public List<User> getUsers() {
      ------
    } 


    4. To produce XML response body, we need to use application/xml media-type.

    @GetMapping(value = "user",  produces = {MediaType.APPLICATION_XML_VALUE})
    @ResponseBody
    public List<User> getUsers() {
      ------
    } 


    The following example creates a Spring Boot web application that returns JSON and XML data to the client.

    Project Directory


    Pom.xml

    <?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
    https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.1</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.knf.dev.demo</groupId>
    <artifactId>spring-responsebody-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-responsebody-example</name>
    <description>Demo project for Spring Boot</description>
    <properties>
    <java.version>17</java.version>
    </properties>
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    </dependencies>

    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>

    </project>


    User.java

    package com.knf.dev.demo.dto;

    public class User {

    private String name;
    private String email;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }
    }


    UserController.java

    package com.knf.dev.demo.controller;

    import com.knf.dev.demo.dto.User;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import java.util.ArrayList;
    import java.util.List;

    @Controller
    @RequestMapping("/api/v1")
    public class UserController {

    // @ResponseBody at method return type level.
    @GetMapping(value = "/example1/users")
    public @ResponseBody List<User> getUsersABC() {

    User user1= new User();
    user1.setEmail("user1@gmail.com");
    user1.setName("John");

    User user2= new User();
    user2.setEmail("user2@gmail.com");
    user2.setName("Sibin");

    List<User> list = new ArrayList<>();
    list.add(user1);
    list.add(user2);
    return list;
    }

    // @ResponseBody at method level
    @GetMapping(value = "/example2/users")
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public List<User> getUsersBCD() {
    User user1= new User();
    user1.setEmail("user1@gmail.com");
    user1.setName("John");

    User user2= new User();
    user2.setEmail("user2@gmail.com");
    user2.setName("Sibin");

    List<User> list = new ArrayList<>();
    list.add(user1);
    list.add(user2);
    return list;
    }
    }


    Run Application - Application.java

    Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.
    Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
    Or you can use the below maven command to run:

    mvn spring-boot:run


    Try to send a GET request to the /example1/users endpoint using Postman to test "@ResponseBody at method return type level"



    Try to send a GET request to the /example2/users endpoint using Postman to test "@ResponseBody at method level".



    Download Source Code

    Popular posts from this blog

    Learn Java 8 streams with an example - print odd/even numbers from Array and List

    Java Stream API - How to convert List of objects to another List of objects using Java streams?

    Registration and Login with Spring Boot + Spring Security + Thymeleaf

    Java, Spring Boot Mini Project - Library Management System - Download

    ReactJS, Spring Boot JWT Authentication Example

    Spring Boot + Mockito simple application with 100% code coverage

    Top 5 Java ORM tools - 2024

    Java - Blowfish Encryption and decryption Example

    Spring boot video streaming example-HTML5

    Google Cloud Storage + Spring Boot - File Upload, Download, and Delete