What is the use of @RestController in Spring MVC?

What is the use of @RestController in Spring MVC?

A) It combines @Controller and @ResponseBody annotations
B) It marks a class as a RESTful controller
C) It is used to create web services in Spring MVC
D) All of the above

Answer:

D) All of the above

Explanation:

The @RestController annotation in Spring MVC is a specialized version of the @Controller annotation. It combines the functionality of the @Controller and @ResponseBody annotations, making it easier to create RESTful web services.

When you annotate a class with @RestController, all the methods within that class automatically have the @ResponseBody behavior, meaning the return values are written directly to the HTTP response body. This eliminates the need to annotate each method with @ResponseBody individually.

For example:


@RestController
public class MyRestController {

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

In this example, the greet() method returns a plain text string, “Hello, RESTful World!”. The @RestController annotation ensures that this string is written directly to the HTTP response body without needing to explicitly use the @ResponseBody annotation.

The @RestController annotation simplifies the creation of RESTful APIs in Spring MVC, making it a key feature when building modern web services.

Reference links:

Spring Boot Tutorial

Leave a Comment

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

Scroll to Top