The 30 second answer
In a servlet application, the server accepts the request and runs it through the filter chain, including Spring Security if configured. DispatcherServlet uses a HandlerMapping to find the controller method and interceptors. A HandlerAdapter resolves arguments, applies validation where requested and invokes the method after interceptor checks. A message converter then writes the response body. If processing throws, HandlerExceptionResolver implementations can route the exception to an @ExceptionHandler, often declared in @ControllerAdvice.
The center of the flow is DispatcherServlet.doDispatch:
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// Determine handler adapter and invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
...
mappedHandler.applyPostHandle(processedRequest, response, mv);
...
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);DispatcherServlet.java L951-L980 (shortened)
Step by step for POST /api/orders:
- Connection. Tomcat's connector accepts the TCP connection, parses HTTP, and runs the request on a worker thread (or a virtual thread if
spring.threads.virtual.enabled=true). - Filters. Servlet filters run in order: for example character encoding, Spring Security's
FilterChainProxy(authentication, authorization), and observation filters. A filter can reject the request before Spring MVC sees it. - **
DispatcherServlet.** It is the front controller, registered by Spring Boot'sDispatcherServletAutoConfiguration. - Handler mapping.
RequestMappingHandlerMappingmatches path, HTTP method, headers and media types to one controller method. It returns aHandlerExecutionChainwith the method and its interceptors. No match gives a 404 (or 405 for a wrong method). - Interceptors.
preHandleruns; returningfalsestops processing. - Handler adapter.
RequestMappingHandlerAdapterresolves each argument withHandlerMethodArgumentResolvers. For@RequestBody OrderRequest req, anHttpMessageConverter(Jackson) reads the JSON;@Validtriggers validation. - Your method runs.
- Return value. For
@ResponseBody/@RestController, a converter writes the result using content negotiation.ResponseEntityalso sets status and headers. - Errors. If anything throws,
processDispatchResulthands the exception toHandlerExceptionResolvers:@ExceptionHandlermethods, thenResponseStatusExceptionhandling, then default Spring MVC exception handling. Unhandled errors go to the servlet container, which forwards to Spring Boot's/errorendpoint (BasicErrorController). - Completion. Interceptor
afterCompletionruns, filters finish, and the thread goes back to the pool.
Interview distinction: filters belong to the servlet container and wrap everything, including DispatcherServlet. Interceptors belong to Spring MVC and only wrap the handler.
Alternate interview scenarios
"Filter vs Interceptor: when would you use each?"
Here the interviewer wants a choice, not the flow. I use a servlet filter for concerns that apply to every request, even ones that never reach a controller. Examples are security, CORS, request logging and correlation IDs, and wrapping the request or response body. A filter only sees the raw request. I use a HandlerInterceptor when I need to know which controller method will run, for example to read an annotation on it, enforce a per-endpoint rule, or time the handler. An interceptor's postHandle does not run if the handler throws, so afterCompletion is the place for cleanup.
"Explain the complete flow and HTTP methods of an addition API."
@RestController
class AdditionController {
record Sum(long sum) {}
@GetMapping(path = "/add", produces = "application/json")
Sum add(@RequestParam("a") int a, @RequestParam("b") int b) {
return new Sum((long) a + b);
}
}This deliberately accepts two int-range operands and widens before addition, so even Integer.MAX_VALUE plus Integer.MAX_VALUE is 4294967294 rather than overflowing as int. If the contract instead promises an int result, use Math.addExact and translate overflow to a documented client error; for arbitrary-precision numbers choose BigInteger and input-size limits. Spring resolves query parameters and converts them to int before invoking the method; a missing required parameter or invalid/out-of-range value normally produces a 400. DispatcherServlet maps GET /add, resolves the arguments, calls add and writes Sum through the JSON converter. A controller advice can standardize errors; security filters may reject the request even earlier. No repository is necessary for a stateless calculation, and introducing a service is an architectural choice, not a framework requirement.
Test 2+3, negative operands, the maximum pair, missing a/b, a non-number, an operand outside int range, unsupported Accept and a wrong HTTP method. Verify both the status and representation. GET supports retrieval semantics and does not justify storing a new record as a side effect. HEAD uses the GET mapping's response metadata but sends no response content; OPTIONS advertises supported methods. Authentication/authorization still follow the service's normal policy, even when the arithmetic is simple.
Sources (9)
- Spring Framework reference: DispatcherServlet special bean typesdocs.spring.io
- Spring Framework reference: DispatcherServlet processingdocs.spring.io
- Spring Framework reference: Interceptiondocs.spring.io
- Spring Boot reference: Error handlingdocs.spring.io
- Spring Framework reference: Filtersdocs.spring.io
- RFC 9110: Method semantics, GET/HEAD/POST and response contentrfc-editor.org
- Spring MVC: Request mapping and HTTP methodsdocs.spring.io
- Spring MVC: RequestParam arguments and type conversiondocs.spring.io
- Java 21 Math.addExactdocs.oracle.com