Skip to content
Spring Boot

Spring

Spring Boot

Spring

Difference Between @Controller,@RestController

admin, January 31, 2025January 31, 2025

In Spring Framework, both @Controller and @RestController are used to define controllers, but they serve different purposes. Here’s the key difference:

1. @Controller

  • It is used in Spring MVC to define a web controller that handles HTTP requests.
  • Typically used for web pages where a view (like JSP, Thymeleaf) is returned.
  • Requires @ResponseBody on methods that return JSON or XML instead of a view.

Example:

@Controller
public class MyController {
@GetMapping("/home")
public String homePage() {
return "home"; // Returns the view name (e.g., home.html or home.jsp)
}

@GetMapping("/data")
@ResponseBody
public String getData() {
return "Hello, World!"; // Returns raw response (without a view)
}
}

2. @RestController

  • Introduced in Spring 4.0 as a specialization of @Controller.
  • It is a combination of @Controller and @ResponseBody, meaning all methods return data directly (usually JSON or XML).
  • No need to use @ResponseBody on each method.

Example:

@RestController
public class MyRestController {

@GetMapping("/greet")
public String greet() {
return "Hello, World!"; // Returns raw response (e.g., JSON or plain text)
}

@GetMapping("/user")
public Map<String, String> getUser() {
Map<String, String> user = new HashMap<>();
user.put("name", "John");
user.put("role", "Admin");
return user; // Returns JSON response
}
}

Key Differences:

Feature@Controller@RestController
View ResolutionReturns a view (e.g., JSP, Thymeleaf)Returns data (JSON/XML)
Implicit @ResponseBodyNo (must be added manually)Yes (applied to all methods)
Use CaseWeb applications (MVC)RESTful APIs

When to Use What?

  • Use @Controller if you are building a traditional web application with views.
  • Use @RestController if you are developing a REST API that returns JSON/XML.

Spring Boot

Post navigation

Previous post
Next post

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

©2025 Spring Boot | WordPress Theme by SuperbThemes