Tuesday, 10 June 2025

@Controller vs @RestController

 In Spring Framework (especially Spring MVC and Spring Boot), both @Controller and @RestController are used to define web controllers, but they behave differently in how they handle responses.

✅ 1. @Controller (Classic MVC Controller)

  • Returns views (like JSP, Thymeleaf).

  • Used in traditional web applications.

  • You typically return a view name, not the response body.

  • To return data (like JSON), you need to use @ResponseBody.

E.g.,
@Controller
public class MyController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello from Controller");
        return "hello"; // returns view "hello.html" or hello.jsp
    }

    @GetMapping("/api/data")
    @ResponseBody
    public String getData() {
        return "This is raw data"; // returns raw response
    }
}

✅ 2. @RestController (Spring 4+ Shortcut for REST APIs)

  • A convenient annotation for RESTful services.

  • Equivalent to @Controller + @ResponseBody on every method.

  • Returns JSON or XML directly (default: JSON).

  • No view resolution.

E.g., 
@RestController
public class MyRestController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello from RestController"; // returned directly as response body
    }

    @GetMapping("/json")
    public Map<String, Object> json() {
        return Map.of("status", "success", "code", 200); // returns as JSON
    }
}

🔍 Comparison Table:

Feature@Controller@RestController
PurposeTraditional MVC (Web UI)REST APIs (returning data)
View Resolver Used?YesNo
JSON Response Default?No (need @ResponseBody)Yes
Introduced InSpring 2.5Spring 4.0
Best Use CaseWeb apps with HTML/JSP/Thymeleaf RESTful web services

✅ When to Use What?

If you're building...Use
A full web UI (JSP, Thymeleaf)      @Controller
A JSON/REST API backend@RestController

No comments:

Post a Comment