@Controller Vs @RestController

🎭 @Controller

✅ Purpose:

Used to serve web pages (like JSP/Thymeleaf/HTML) — it returns views.

📦 Common Use Case:

@Controller
public class ViewController {
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "Aftab");
        return "hello"; // Returns view name like hello.html or hello.jsp
    }
}

📌 Key Points:

Feature Value
Returns View names (String)
Used With Thymeleaf, JSP, etc.
Response Body Not returned by default
Extra Required Use @ResponseBody to return data instead


🔁 @RestController

✅ Purpose:

Used for REST APIs — it returns JSON or XML response directly to the client.

📦 Common Use Case:

@RestController
public class ApiController {
    @GetMapping("/api/greet")
    public String greet() {
        return "Hello from API"; // Returns raw string or JSON
    }
}

📌 Key Points:

@RestController
public class ApiController {
    @GetMapping("/api/greet")
    public String greet() {
        return "Hello from API"; // Returns raw string or JSON
    }
}

🔍 Side-by-Side Comparison

Feature @Controller @RestController
Returns View (HTML) ✅ Yes ❌ No
Returns JSON/XML ❌ (needs @ResponseBody) ✅ By default
Use Case Web UI (Thymeleaf, JSP) REST APIs (JSON, mobile, frontend)
Includes @ResponseBody ❌ (optional) ✅ Implicitly included
Response Format View name (e.g., index.html) Raw data (e.g., JSON, XML)


✅ Summary

Annotation Purpose Automatically Adds @ResponseBody?
@Controller MVC / web page rendering ❌ No
@RestController REST API (data exchange) ✅ Yes
Back to blog

Leave a comment