Thursday, 3 July 2025

DispatcherServlet in springboot / spring framework with annotations

✅ What is DispatcherServlet?

DispatcherServlet is the Front Controller in the Spring MVC architecture. It is a subclass of HttpServlet and serves as the entry point for all HTTP requests in a Spring web application.


๐Ÿ“Œ Responsibilities of DispatcherServlet

It intercepts all incoming HTTP requests and delegates them to the appropriate components for further processing, using annotations such as:

  • @Controller

  • @RequestMapping

  • @GetMapping, @PostMapping, etc.


⚙️ Internal Delegation Flow

DispatcherServlet coordinates the entire web request handling by delegating to various components:

1. HandlerMapping

  • Purpose: Determines which @Controller and method should handle the request.

  • Examples:

    • RequestMappingHandlerMapping

    • BeanNameUrlHandlerMapping

2. HandlerAdapter

  • Purpose: Invokes the matched controller method with appropriate arguments.

  • Examples:

    • RequestMappingHandlerAdapter

3. ViewResolver

  • Purpose: Resolves the logical view name (like "home") to a physical view (like /WEB-INF/views/home.jsp).

  • Examples:

    • InternalResourceViewResolver

    • ThymeleafViewResolver

4. HandlerExceptionResolver

  • Purpose: Handles any exceptions thrown during controller execution and maps them to error views or responses.

  • Examples:

    • DefaultHandlerExceptionResolver

    • ResponseStatusExceptionResolver


๐Ÿšฆ DispatcherServlet Request Flow with Annotations

text
Browser Request ↓ [ DispatcherServlet ] ← Auto-configured servlet ↓ HandlerMapping → Matches @RequestMapping, @GetMapping, etc. ↓ @Controller / @RestController method ↓ ResponseBody / ViewResolver → JSON, HTML, JSP, Thymeleaf ↓ HTTP Response

✅ DispatcherServlet with Spring Annotations

1. @Controller or @RestController

Used to define a controller class that handles web requests.

java
@RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello from Spring!"; } }
  • @RestController = @Controller + @ResponseBody


2. @RequestMapping, @GetMapping, @PostMapping, etc.

Used to map HTTP requests to handler methods.

java
@GetMapping("/hello") // Shortcut for @RequestMapping(method = GET) public String sayHello() { ... }

3. @ResponseBody

Binds the return value directly to the HTTP response body.

java
@Controller public class MyController { @ResponseBody @GetMapping("/data") public String jsonResponse() { return "{\"message\": \"OK\"}"; } }

4. @RequestParam, @PathVariable, @RequestBody

These help extract data from the request.

java
@GetMapping("/user/{id}") public String getUser(@PathVariable int id) { ... } @PostMapping("/user") public String saveUser(@RequestBody User user) { ... }

5. @ExceptionHandler

Used to handle exceptions in the controller layer.

java
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleEx(Exception ex) { return ResponseEntity.status(500).body("Error: " + ex.getMessage()); } }

✅ How DispatcherServlet is Registered (Spring Boot)

In Spring Boot, DispatcherServlet functions exactly the same as in traditional Spring MVC, but Spring Boot auto-configures and registers it for you, simplifying setup.


๐Ÿ”ง Spring Boot Auto-Configuration

When you create a Spring Boot web application (with spring-boot-starter-web), Spring Boot:

  • Automatically registers DispatcherServlet as a bean.

  • Automatically maps it to the root path (/) using the DispatcherServletRegistrationBean.

  • Sets up default HandlerMapping, HandlerAdapter, ViewResolver, and ExceptionResolvers.


๐Ÿ“ Default DispatcherServlet URL Mapping

properties
# application.properties spring.mvc.servlet.path=/ # Default mapping for DispatcherServlet

You can change it:

properties
spring.mvc.servlet.path=/api/*

๐Ÿงต Customizing DispatcherServlet in Spring Boot

If needed, you can override the default DispatcherServlet bean:

java
@Bean public DispatcherServlet dispatcherServlet() { DispatcherServlet servlet = new DispatcherServlet(); servlet.setThrowExceptionIfNoHandlerFound(true); // Customize behavior return servlet; }

To register it manually (optional):

java
@Bean public ServletRegistrationBean<DispatcherServlet> registration(DispatcherServlet dispatcherServlet) { ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<>(dispatcherServlet); registration.setLoadOnStartup(1); registration.addUrlMappings("/custom/*"); return registration; }

๐Ÿ”ง Properties (optional in application.properties)

properties
spring.mvc.servlet.path=/api # DispatcherServlet mapped to /api/* spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp

✅ Summary of Key Annotations Involved with DispatcherServlet

AnnotationPurpose
@ControllerMarks a class as a web controller
@RestControllerSame as @Controller but returns response body directly
@RequestMappingMaps request URL to method
@GetMapping, @PostMappingSpecialized shortcuts for specific HTTP methods
@ResponseBodyReturns data directly to HTTP response
@RequestParamGets query parameters
@PathVariableExtracts values from the URL
@RequestBodyBinds JSON body to method param
@ExceptionHandlerHandles exceptions at controller level

๐Ÿ” DispatcherServlet with Annotations - Simple Spring Boot Example

java
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } @RestController @RequestMapping("/api") public class SampleController { @GetMapping("/greet") public String greet(@RequestParam String name) { return "Hello, " + name; } }