The difference between `@RestController` and `@Controller`
The difference between @RestController and @Controller in Spring Framework lies mainly in how they handle HTTP responses. 1. @Controller Used for: Traditional MVC (Model-View-Controller) web applications. Returns: Usually returns a View (like JSP, Thymeleaf, etc.). ResponseBody: If you want to return JSON/XML instead of a view, you must use @ResponseBody on the method. Example: @Controller public class MyController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello, World!"); return "hello"; // returns a view named "hello" } @GetMapping("/api") @ResponseBody public String api() { return "This is JSON or plain text"; } } 2. @RestController Used for: RESTful web services (APIs). Returns: Automatically returns JSON or XML responses. Behavior: It is a convenience annotation that combines @Controller and @ResponseBody. So every method returns the body directly, not a view. Example: @RestController public class MyRestController { @GetMapping("/hello") public String hello() { return "Hello, REST!"; // returns as JSON or plain text } } Summary: Feature @Controller @RestController Returns View? Yes (by default) No JSON/XML by default? No (@ResponseBody needed) Yes Use case Web UI applications REST APIs Combines with @ResponseBody Already includes @ResponseBody

The difference between @RestController
and @Controller
in Spring Framework lies mainly in how they handle HTTP responses.
1. @Controller
- Used for: Traditional MVC (Model-View-Controller) web applications.
- Returns: Usually returns a View (like JSP, Thymeleaf, etc.).
-
ResponseBody: If you want to return JSON/XML instead of a view, you must use
@ResponseBody
on the method.
Example:
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, World!");
return "hello"; // returns a view named "hello"
}
@GetMapping("/api")
@ResponseBody
public String api() {
return "This is JSON or plain text";
}
}
2. @RestController
- Used for: RESTful web services (APIs).
- Returns: Automatically returns JSON or XML responses.
-
Behavior: It is a convenience annotation that combines
@Controller
and@ResponseBody
. So every method returns the body directly, not a view.
Example:
@RestController
public class MyRestController {
@GetMapping("/hello")
public String hello() {
return "Hello, REST!"; // returns as JSON or plain text
}
}
Summary:
Feature | @Controller |
@RestController |
---|---|---|
Returns View? | Yes (by default) | No |
JSON/XML by default? | No (@ResponseBody needed) |
Yes |
Use case | Web UI applications | REST APIs |
Combines with | @ResponseBody |
Already includes @ResponseBody
|