1
@RestController vs @Controller
In Spring MVC, both @RestController and @Controller are used to define controller classes, but
they have some differences in their behavior and purpose.
1. Purpose:
● @Controller: It is typically used for traditional web applications that serve HTML
pages and handle HTTP requests by returning views (HTML templates).
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/greeting")
public ModelAndView greeting() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("greeting");
modelAndView.addObject("message", "Hello, World!");
return modelAndView;
● @RestController: It is specifically designed for building RESTful APIs that primarily
deal with JSON or XML responses. It automatically serializes/deserializes Java
objects to/from JSON or XML format.
2
Example
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/greeting")
public ResponseEntity<String> greeting() {
String message = "Hello, World!";
return ResponseEntity.ok(message);
2. Response Handling:
● @Controller: Controller methods are responsible for handling requests and
returning a logical view name or a ModelAndView object, which represents a view
template and model data.
● @RestController: Controller methods annotated with @RestController return the
response directly as JSON or XML, eliminating the need for explicit view resolution.
The return type of the methods is serialized and sent as the response body.
3. Shortcut for Annotations:
3
● @Controller: The @Controller annotation is a specialization of the @Component
annotation. It allows the component scanning mechanism to detect and register the
controller class as a Spring bean.
● @RestController: The @RestController annotation combines the @Controller and
@ResponseBody annotations. It is a convenient shortcut to annotate a controller class
that is primarily used for RESTful APIs. The @ResponseBody annotation is not
required on individual methods when using @RestController.
4. Return Types:
● @Controller: Controller methods can return various types such as String (view
name), ModelAndView, View, or ResponseEntity.
● @RestController: Controller methods typically return the actual data to be serialized
as the response body. They commonly use return types like String, List, Map, or
custom objects. Spring automatically serializes the return value to JSON or XML
based on the requested media type.
In summary, the choice between @Controller and @RestController depends on the purpose of
your application. If you're building a traditional web application with server-side rendering, use
@Controller. For building RESTful APIs that primarily deal with JSON or XML responses, use
@RestController to simplify the development process by automatically handling serialization and
deserialization.