Controller and RestController
In the Spring framework, @Controller
and @RestController
are used to define controllers, but they serve different purposes and are used in different scenarios:
@Controller
- Purpose: Used to define a standard web controller in Spring MVC.
- Response Handling: Typically returns a view (like an HTML page) using a view resolver.
- Usage: Suitable for web applications where the response is usually an HTML page.
- Example:
@Controller @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public String displayUserInfo(@PathVariable Long id) { // logic to get user info return "userView"; // returns the view name } }
@RestController
- Purpose: A specialized version of
@Controller
used to create RESTful web services. - Response Handling: Combines
@Controller
and@ResponseBody
, so it returns data directly (like JSON or XML) instead of a view. - Usage: Ideal for REST APIs where the response is typically JSON or XML.
- Example:
@RestController @RequestMapping("/users") public class UserRestController { @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { // logic to get user info return new User(id, "John Doe"); // returns the user object as JSON } }
In summary, @Controller
is used for traditional web applications that return views, while @RestController
is used for RESTful web services that return data directly in formats like JSON or XML.
References:
- Spring @Controller Vs. @RestController: What’s Difference? - HowToDoInJava
- The Spring @Controller and @RestController Annotations
- What is the Difference Between @Controller and @RestController in …
- What is the difference between @Controller vs @RestController in Spring …
- Spring Framework: @RestController vs. @Controller - DZone