@Controller vs @RestController in Spring MVC
Fast recall
Quick revision
Core answer
Understanding of Spring's composed annotations and the difference between traditional MVC and RESTful responses
Using @Controller for REST endpoints and forgetting @ResponseBody on every method, causing view resolution errors
Explain that @RestController is a meta-annotation combining @Controller and @ResponseBody, and describe Jackson's role
Interview-ready guide
Interview answer
A Thymeleaf controller can return the view name orders and add data to Model. An API controller can return OrderDto from @RestController and let a converter write the negotiated representation. A mixed @Controller can use ordinary view-returning methods and add @ResponseBody on a health or download method. The distinction is return-value handling, not 'Controller always HTML and RestController always Jackson JSON'.
@Controller vs @RestController in Spring MVC
Direct Answer
@Controller marks a Spring MVC controller; its methods can render views or write response bodies. @RestController combines @Controller with class-level @ResponseBody, so its handler return values are written through HttpMessageConverters by default. JSON is common but not required. A @Controller method can also return data by adding @ResponseBody or ResponseEntity.
Code Example
// @Controller — returns a VIEW NAME, resolved to HTML by ViewResolver
@Controller
class PageController {
@GetMapping("/home")
public String home(Model model) {
model.addAttribute("user", "Alice");
return "home"; // -> templates/home.html (Thymeleaf)
}
}
// @RestController = @Controller + @ResponseBody — returns DATA as JSON
@RestController
@RequestMapping("/api")
class UserApi {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "Alice"); // -> {"id":1,"name":"Alice"}
}
}
record User(Long id, String name) {}
The same DispatcherServlet routes both — only the implicit @ResponseBody behavior differs.
Common Mistakes & Pitfalls
- Forgetting @ResponseBody: Using @Controller for REST endpoints and not adding @ResponseBody to methods. Spring tries to resolve the returned object as a view name, resulting in "template not found" errors. You see 404s or "Could not resolve view" exceptions.
- Mixing Annotations: Using @RestController but trying to return view names — doesn't work because @ResponseBody is applied to all methods.
- Not Understanding Jackson: Freshers don't realize @RestController triggers automatic JSON serialization. They manually build JSON strings or use ObjectMapper explicitly when Jackson does it automatically for POJOs.
Check your understanding
Answer these without looking back at the article.
- What is @ResponseBody and what does it do?
- How does Spring decide which HttpMessageConverter to use?
- Can you mix @Controller and @RestController behavior in one class?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.