Introduction of @Controller in SpringMVC

 

✅ Purpose of @Controller in Spring MVC

In Spring MVC, @Controller is a key annotation that marks a Java class as a web controller — it handles HTTP requests from clients (like browsers) and returns views (HTML, JSP, etc.) or data.


🎯 Real-World Analogy:

Think of:

  • Browser = A customer placing an order.

  • DispatcherServlet = A receptionist receiving the order.

  • @Controller class = A chef (who prepares the dish).

  • View (HTML page) = The served dish.


🔄 Spring MVC Request Flow with @Controller

Browser (HTTP GET /home)
        |
        v
DispatcherServlet (Front Controller)
        |
        v
HandlerMapping → Finds matching @Controller method
        |
        v
HomeController.home() executes
        |
        v
Returns logical view name ("home")
        |
        v
ViewResolver maps it to /templates/home.html
        |
        v
Thymeleaf renders the view with model data
        |
        v
Final HTML sent back to browser



📦 Components in Spring MVC Architecture:

Component

Role

DispatcherServlet

Front controller – receives all web requests

@Controller

Handles request and business logic

Model

Sends data from controller to view

ViewResolver

Resolves view name to actual template (like home.html)

View (Thymeleaf/JSP)

Renders HTML page using the model data


🧪 Example in Code

1. Controller class

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome to Spring MVC!");
        return "home"// Logical view name
    }
}



2. View (home.html)

<h1 th:text="${message}">Default message</h1>



🧠 Step-by-Step Working (Technical Breakdown)

Step

Description

1

User hits http://localhost:8080/home

2

DispatcherServlet intercepts the request (configured in web.xml or auto via Spring Boot)

3

It uses HandlerMapping to map the URL /home to HomeController.home()

4

Method executes, adds message to the model

5

Returns "home" – logical name of view

6

ViewResolver maps "home" to /templates/home.html

7

ThymeleafView renders the view using model data

8

Response (HTML page) is sent back to browser


📌 DispatcherServlet in Action

The DispatcherServlet is auto-configured in Spring Boot and acts as:

  • Request handler

  • Dispatcher to controllers

  • View resolver

In traditional XML config:

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>


In Spring Boot, it's auto-registered via @SpringBootApplication.




🧩 Summary Table

Term

Meaning

@Controller

Handles requests and returns view

@GetMapping

Maps GET request to controller method

Model

Passes data from controller to view

DispatcherServlet

Central dispatcher for all web requests

ViewResolver

Resolves view name to file

Thymeleaf/JSP

Template engine to generate HTML





In Spring MVC/Spring Boot, there are multiple controller variants, each serving a slightly different purpose based on how you want to handle HTTP requests and responses (e.g., returning HTML, JSON, or both).

Here's a breakdown of the different controller annotations (or variants of controllers) in Spring:


✅ 1. @Controller

  • Purpose: Used to return views (e.g., HTML pages via Thymeleaf, JSP).

  • Common in: Web applications with UI.

  • Return Type: String (view name).

  • Requires @ResponseBody if you want to return raw data like JSON.

✅ Example:

@Controller
public class PageController {
   
    @GetMapping("/welcome")
    public String welcome(Model model) {
        model.addAttribute("msg", "Hello HTML View!");
        return "welcome"// Returns welcome.html
    }
}



✅ 2. @RestController

  • Purpose: Used to create REST APIs.

  • Common in: Microservices or backend services.

  • Return Type: JSON or XML (data).

Internally:


@Controller + @ResponseBody


✅ Example:

@RestController
public class ApiController {

    @GetMapping("/api/hello")
    public String sayHello() {
        return "Hello JSON!";
    }
}



✅ 3. @ControllerAdvice

  • Purpose: A global controller that handles:

    • Global exception handling

    • Global data binding

    • Model attributes for multiple controllers

  • Think of it as an interceptor or helper for all controllers.

✅ Example:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleAllExceptions(Exception ex, Model model) {
        model.addAttribute("error", ex.getMessage());
        return "error"// Returns error.html
    }
}



✅ 4. @RestControllerAdvice (since Spring 4.3+)

  • Purpose: Same as @ControllerAdvice, but for REST APIs (i.e., returns JSON instead of views).

Equivalent to:


@ControllerAdvice + @ResponseBody


✅ Example:

@RestControllerAdvice
public class GlobalRestExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public Map<String, String> handleRuntimeException(RuntimeException ex) {
        return Map.of("error", ex.getMessage());
    }
}



✅ 5. @RequestController (🔸Not a standard annotation)

  • ❗ This does not exist in Spring officially.

  • Sometimes confused with other frameworks or pseudo-annotations.


✅ Comparison Summary Table:

Annotation

Returns

Use Case

Extra Notes

@Controller

View (HTML)

MVC web apps

Use with template engine (Thymeleaf)

@RestController

JSON/XML

REST APIs

No need to use @ResponseBody

@ControllerAdvice

View (Global)

Global MVC config

Handles exceptions across controllers

@RestControllerAdvice

JSON/XML

Global REST handling

REST API-specific error handling


Bonus: @ModelAttribute in Controllers

  • Use this inside @Controller to bind form data.

  • Can also prepopulate model attributes globally.


Would you like a visual diagram showing how all these controller variants interact in Spring Boot?


Distributed by Gooyaabi Templates | Designed by OddThemes