@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