Junior
What is the difference between RestController and Controller?
sobes.tech AI
Answer from AI
@Controller is used for handling web requests and returns view names (.jsp, .html, etc.). It is often used in MVC architecture, where it manages interaction with the data model and selects the view for display.
@RestController is a specialized version of @Controller. It automatically converts the return values of methods into HTTP response formats, usually JSON or XML. This is achieved through the automatic inclusion of @ResponseBody for each method within the controller. @RestController is more commonly used for creating RESTful web services that provide data in raw form rather than returning HTML pages.
| Characteristic | @Controller |
@RestController |
|---|---|---|
| Purpose | Handling web requests, returning views | Creating RESTful web services, returning data (JSON, XML) |
@ResponseBody |
Requires explicit use for each method returning data | Automatically applied to all methods |
| Return type | View name (String), ModelAndView | Data (objects, List, etc.), automatically serialized |
Example:
@Controller:
// Example of using @Controller
@Controller
@RequestMapping("/view")
public class ViewController {
@GetMapping("/hello")
public String sayHello() {
return "hello"; // Returns view name (e.g., hello.jsp)
}
}
@RestController:
// Example of using @RestController
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/user")
public User getUser() {
// Assume there is a User class
return new User("John Doe", 30); // Returns JSON representation of User object
}
}