What is the purpose of the @ResponseBody annotation in Spring MVC?

What is the purpose of the @ResponseBody annotation in Spring MVC?

A) To bind HTTP request parameters to method arguments
B) To return the response body directly from a controller method
C) To specify the HTTP status code for a response
D) To handle exceptions in a Spring MVC application

Answer:

B) To return the response body directly from a controller method

Explanation:

The @ResponseBody annotation in Spring MVC is used to indicate that the return value of a controller method should be written directly to the HTTP response body. This annotation is typically used when building RESTful web services, where the response body is often in JSON or XML format.

For example:


@Controller
public class MyController {

    @GetMapping("/greet")
    @ResponseBody
    public String greet() {
        return "Hello, World!";
    }
}

In this example, the greet() method returns a plain text string, “Hello, World!”. The @ResponseBody annotation ensures that this string is written directly to the HTTP response body, rather than being interpreted as a view name.

The @ResponseBody annotation is essential when returning data directly from a controller method, especially in REST APIs where the response is often serialized as JSON or XML.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top