@Controller vs @RestController in Spring Boot: Key Differences with Examples

    @Controller vs @RestController in Spring Boot: Key Differences with Examples

    Learn the difference between @Controller and @RestController in Spring Boot with real examples, use cases, and beginner-friendly explanations. Master when and how to use each annotation to build web pages or RESTful APIs effectively.

    default profile

    Shreya Adak

    February 14, 2025

    5 min read

    If you are a beginner in Spring Boot, there is a high chance you might get confused between @Controller and @RestController. Because they sound similar right? And to be honest when I first started learning Spring Boot, I was confused too. But now, I clearly understand the difference between them.

    So in this article, I’m going to explain the difference between @Controller and @RestController, so that the next time you see these annotations, you will have a clear idea in your mind. I have also included code snippets to help you understand better. So, let’s jump into it!

    Overview of @Controller#

    The @Controller annotation is part of the Spring MVC framework and is used to mark a class as a web controller. It is typically used to handle HTTP requests and return views (e.g., HTML pages) or data to be rendered by a view resolver. This annotation is ideal for traditional web applications where the response is often a rendered webpage.

    • Purpose: Handles HTTP requests and returns a view or data to be processed by a view resolver.
    • Response Type: Typically returns a String representing the name of a view (e.g., a JSP or Thymeleaf template) or a ModelAndView object.
    • Use Case: Suited for applications that serve web pages or need to integrate with a view technology.
    • Annotation Composition: @Controller is a specialization of the @Component annotation, enabling the class to be auto-detected by Spring’s component scanning.

    Example of @Controller#

    import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MyController { @GetMapping("/welcome") public String welcome(Model model) { model.addAttribute("message", "Welcome to Spring Boot!"); return "welcome"; // Returns the name of the view (e.g., welcome.html) } }

    In this example, the @Controller annotation marks the class as a web controller. The welcome method handles a GET request to /welcome, adds a message to the model, and returns the name of a view (welcome). Spring’s view resolver will map this to a template (e.g., welcome.html) for rendering.

    Overview of @RestController#

    The @RestController annotation, introduced in Spring 4.0, is a specialized version of @Controller designed for RESTful web services. It combines @Controller and @ResponseBody, meaning that the return value of a method is automatically serialized into the HTTP response body (typically as JSON or XML) without requiring a view resolver.

    • Purpose: Handles HTTP requests and returns data directly in the response body, typically in JSON or XML format.
    • Response Type: Returns objects that are serialized into JSON/XML by Spring’s HttpMessageConverter.
    • Use Case: Ideal for building REST APIs where the client expects data rather than rendered views.
    • Annotation Composition: @RestController is a convenience annotation that combines @Controller and @ResponseBody.

    Example of @RestController#

    import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyRestController { @GetMapping("/api/greeting") public String greeting() { return "Hello, Spring Boot!"; } }

    In this example, the @RestController annotation marks the class as a REST controller. The greeting method handles a GET request to /api/greeting and returns a String that is directly written to the HTTP response body as plain text or JSON (depending on the configuration).

    Key Differences Between @Controller and @RestController#

    Here is a detailed comparison of @Controller and @RestController based on various aspects:

    Aspect@Controller@RestController
    PurposeUsed for traditional web applications to return views or templates.Used for RESTful APIs to return data (e.g., JSON/XML) directly.
    Annotation CompositionOnly includes @Controller (a specialization of @Component).Combines @Controller and @ResponseBody.
    Response HandlingReturns view names or ModelAndView for rendering by a view resolver.Returns objects serialized into the response body (e.g., JSON/XML).
    View ResolverRequires a view resolver to map view names to templates (e.g., Thymeleaf, JSP).Does not use a view resolver; responses are serialized directly.
    Use CaseWeb applications with server-side rendering (e.g., serving HTML pages).REST APIs for mobile apps, single-page applications (SPAs), or microservices.
    Method-Level AnnotationRequires @ResponseBody to return data directly in the response body.@ResponseBody is implicit for all methods; no need to specify.

    When to Use @Controller vs. @RestController#

    Use @Controller:

    When I work on a Spring Boot project that needs to show HTML pages, I use @Controller. It’s perfect for traditional web apps where you want to return a full webpage instead of just data.

    This annotation works well with template engines like Thymeleaf, JSP, or FreeMarker. I just return the name of the view (like an HTML file), and Spring Boot takes care of showing it to the user.

    For example, if I’m building a website where users can browse a list of products, I’d use @Controller to handle the request and return a Thymeleaf page that displays the products nicely.

    Use @RestController:

    On the other hand, I use @RestController when I’m building REST APIs that send data like JSON or XML to the client.

    What I like about @RestController is that it makes things easier because I don’t need to add @ResponseBody to every method. It automatically takes whatever I return (like an object) and converts it into a proper response, usually in JSON format.

    For example, if I’m creating an API for a mobile app that needs user profile data, I would use @RestController to return that data directly as JSON.

    Combining @Controller and @RestController in a Single Application#

    In some Spring Boot applications, you may need both @Controller and @RestController. For example:

    • Use @Controller for serving web pages to users (e.g., a login page or dashboard).
    • Use @RestController for providing API endpoints that the frontend (e.g., a React or Angular app) consumes.

    Example of Combined Usage#

    import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @Controller class WebController { @GetMapping("/home") public String home(Model model) { model.addAttribute("title", "Home Page"); return "home"; // Returns home.html } } @RestController class ApiController { @GetMapping("/api/data") public String getData() { return "{\\"message\\": \\"API Data\\"}"; } }

    In this example, WebController serves a webpage, while ApiController provides a REST API endpoint.

    Conclusion#

    In short, The @Controller is used to return view pages, while @RestController is used to return data, typically in JSON or XML format. It also includes @ResponseBody by default so you don’t need to add again where we use @RestController annotation. I hope you now have a clear picture of the difference between @Controller and @RestController, and the next time you see these annotations, you will have a proper understanding of what they do.

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more
    Spring Boot
    Difference Between @Controller And @Restcontroller
    Spring Boot Rest API
    Spring Boot Annotations

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

    More articles