Sobes.tech
Junior — Middle

What is the difference between @RestController and @Controller annotations in Spring?

sobes.tech AI

Answer from AI

The @Controller annotation is used to define a Spring MVC component that handles HTTP requests and returns the name of a view, such as JSP or HTML. To return data (e.g., JSON), you need to additionally use @ResponseBody on the methods.

@RestController is a specialized annotation that combines @Controller and @ResponseBody. It automatically serializes the returned objects into JSON or XML and sends them in the HTTP response body, which is convenient for creating REST APIs.

Example:

@RestController
public class MyRestController {
    @GetMapping("/api/data")
    public MyData getData() {
        return new MyData("value"); // automatically converted to JSON
    }
}

@Controller
public class MyController {
    @GetMapping("/page")
    public String getPage(Model model) {
        model.addAttribute("attr", "value");
        return "pageView"; // returns the view name
    }
}
What is the difference between @RestController and… - sobes.tech