@Controller & @RestController

Anil R
1 min readNov 19, 2024

--

In Spring Boot, @Controller and @RestController are annotations used to define controllers in a Spring MVC application. Both serve different purposes based on the type of response you want to return.

1. @Controller

  • Used to define a web controller that processes HTTP requests and returns views (e.g., HTML, JSP, or Thymeleaf templates).
  • Works with view resolvers like Thymeleaf or JSP to render the UI.
  • Typically used in MVC-based web applications.

Key Characteristics

  • Maps HTTP requests to handler methods using annotations like @RequestMapping or @GetMapping.
  • The handler methods return:
  • A view name (String) that gets resolved by the view resolver.
  • A Model or ModelAndView object for passing data to the view.

2. @RestController

  • A specialization of @Controller that is used to create RESTful web services.
  • Combines @Controller and @ResponseBody.
  • By default, all methods return JSON/XML data directly in the HTTP response body instead of resolving a view.
  • Typically used in API-based applications.

Key Characteristics

  • No need to annotate each method with @ResponseBody; it's implicit.
  • Ideal for building REST APIs where the response is data (e.g., JSON, XML).

When to Use Which?

  • Use @Controller when building web applications that require rendering views (HTML, JSP, etc.).
  • Use @RestController when building RESTful APIs to return JSON/XML responses to clients.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet