Spring / Spring7 Intermediate to Advanced Interview questions
Explain the internal working of the DispatcherServlet request-handling flow in Spring MVC?
DispatcherServlet coordinates a well-defined internal pipeline for every request, delegating to a series of collaborator components rather than handling anything itself.
sequenceDiagram
participant C as Client
participant DS as DispatcherServlet
participant HM as HandlerMapping
participant HA as HandlerAdapter
participant Ctrl as Controller
participant VR as ViewResolver/Converter
C->>DS: HTTP Request
DS->>HM: resolve handler
HM-->>DS: HandlerExecutionChain
DS->>HA: invoke handler
HA->>Ctrl: call controller method
Ctrl-->>HA: return value
HA-->>DS: ModelAndView or body
DS->>VR: resolve view / convert body
VR-->>C: HTTP Response
First, a HandlerMapping (typically RequestMappingHandlerMapping) matches the request URL and method to a HandlerExecutionChain, bundling the target controller method with any applicable interceptors. A HandlerAdapter then runs each interceptor's preHandle, resolves the controller method's arguments via registered HandlerMethodArgumentResolvers (path variables, request bodies, headers), and invokes the method.
The return value is processed by a matching HandlerMethodReturnValueHandler: for a traditional @Controller, a returned view name becomes a ModelAndView that a ViewResolver later resolves and renders; for @ResponseBody/@RestController, the object is instead handed directly to an HttpMessageConverter to be serialized straight into the response. Interceptors' postHandle and afterCompletion callbacks run afterward, and if any step throws, the configured chain of HandlerExceptionResolvers - including the one backing @ExceptionHandler methods - gets a chance to convert the exception into a proper response before it becomes a generic error.
More Related questions...