@ResponseBody
@Controller
@RestController
Let’s learn these step by step with analogy, code examples, and clear differences.
🧠 First, Understand the Basics:
📌 @Controller
Used to create Web Pages (like HTML using Thymeleaf).
📌 @RestController
Used to create REST APIs (returns JSON or plain text, not HTML).
📌 @ResponseBody
Tells Spring:
"Don't return a view (HTML page). Instead, return the actual data (like JSON or String) in the HTTP
response body."
✅ Analogy
Imagine you're a waiter in a restaurant:
Annotation What It Does
@Controller Returns a view page (like an HT
@ResponseBody Returns data (JSON/text) instea
@RestController Combines @Controller + @Re
💡 1. @Controller Example (Returns HTML View)
java Copy Edit
@Controller public class PageController { @GetMapping("/home") public String homePage() {
return "home"; // returns "home.html" page from templates folder } }
✅ You must have a file home.html in src/main/resources/templates .
💡 2. @Controller + @ResponseBody Example (Returns Text)
java Copy Edit
@Controller public class HelloController { @GetMapping("/hello") @ResponseBody public
String sayHello() { return "Hello, Naziya!"; } }
✅ This returns plain text:
Copy Edit
Hello, Naziya!
No HTML file needed.
💡 3. @RestController Example (Shortcut for JSON APIs)
java Copy Edit
@RestController public class ApiController { @GetMapping("/api/welcome") public String
welcome() { return "Welcome to Spring Boot REST API!"; } }
✅ Same output as above, but simpler. No need to write @ResponseBody .
🎯 Summary Table
Annotation Returns
@Controller HTML Page
@Controller + @ResponseBody Text or JSON
@RestController Text or JSON
✅ When to Use What?
Use @Controller when building a web page (like login page, dashboard).
Use @RestController when building a REST API (for frontend, mobile apps, Postman, etc).
Use @ResponseBody only if you want to return data from a @Controller class.