RestController vs Controller in Spring Applications: What’s the Difference?
When building web applications with Spring, developers often wonder: Should I use @Controller or @RestController? Both annotations define web components, but they serve different purposes. Understanding the distinction is crucial for designing clean, maintainable applications.
1. What is @Controller?
@Controller is part of Spring MVC and is primarily used for server-side rendering. It works with view technologies like Thymeleaf, JSP, or FreeMarker.
- Purpose: Return views (HTML pages) to the client.
- Behavior: Methods typically return a String representing the view name.
- Data Handling: Use
ModelorModelAndViewto pass data to the view.
Example:
@Controller
public class PageController {
@GetMapping("/home")
public String home(Model model) {
model.addAttribute("message", "Welcome!");
return "home"; // Resolved by ViewResolver
}
@GetMapping("/status")
@ResponseBody
public Map<String, String> status() {
return Map.of("status", "ok");
}
}
2. What is @RestController?
@RestController is designed for RESTful APIs. It combines @Controller and @ResponseBody, meaning every method returns data directly (usually JSON) instead of a view.
- Purpose: Build REST APIs for SPAs, mobile apps, or microservices.
- Behavior: Methods return objects, which Spring serializes using HttpMessageConverters (e.g., Jackson for JSON).
Example:
@RestController
@RequestMapping("/api")
public class UserApi {
@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(id, "Alice");
}
}
3. Key Differences
| Feature | @Controller | @RestController |
|---|---|---|
| Default Behavior | Returns view name | Returns JSON/XML |
| View Rendering | ✅ Yes | ❌ No |
| Needs @ResponseBody | Yes (for JSON) | No (implicit) |
| Typical Use Case | MVC web pages | REST APIs |
4. When to Use Which?
- Use @Controller if you’re building traditional web pages with server-side rendering.
- Use @RestController if you’re exposing REST endpoints for front-end apps or other services.
5. Common Pitfalls
- Returning a view name from
@RestControllerwill send"home"as JSON, not render a page. - Forgetting
@ResponseBodyin@Controllerwhen returning JSON will cause view resolution errors.
Conclusion
Both annotations are powerful, but they serve different roles. For modern applications with APIs, @RestController is the go-to choice. For classic MVC apps, stick with @Controller.