Spring Boot learning path Level 3 This level · 6 of 9
Hard java spring

What happens internally when you hit a REST endpoint?

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.

Could you say this in an interview?

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:

  1. 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).
  2. 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.
  3. **DispatcherServlet.** It is the front controller, registered by Spring Boot's DispatcherServletAutoConfiguration.
  4. Handler mapping. RequestMappingHandlerMapping matches path, HTTP method, headers and media types to one controller method. It returns a HandlerExecutionChain with the method and its interceptors. No match gives a 404 (or 405 for a wrong method).
  5. Interceptors. preHandle runs; returning false stops processing.
  6. Handler adapter. RequestMappingHandlerAdapter resolves each argument with HandlerMethodArgumentResolvers. For @RequestBody OrderRequest req, an HttpMessageConverter (Jackson) reads the JSON; @Valid triggers validation.
  7. Your method runs.
  8. Return value. For @ResponseBody/@RestController, a converter writes the result using content negotiation. ResponseEntity also sets status and headers.
  9. Errors. If anything throws, processDispatchResult hands the exception to HandlerExceptionResolvers: @ExceptionHandler methods, then ResponseStatusException handling, then default Spring MVC exception handling. Unhandled errors go to the servlet container, which forwards to Spring Boot's /error endpoint (BasicErrorController).
  10. Completion. Interceptor afterCompletion runs, 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."
Pure addition is a safe, idempotent calculation, so a simple contract is GET /add?a=2&b=3 returning 200 and {"sum":5}. It does not need POST, PUT and DELETE merely because a CRUD example used those methods. If the operation creates a saved calculation resource, POST /calculations with a request body is a different contract, commonly returning 201 and a Location. Choose the method from semantics, not from whether inputs happen to be numbers.

@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)
  1. Spring Framework reference: DispatcherServlet special bean typesdocs.spring.io
  2. Spring Framework reference: DispatcherServlet processingdocs.spring.io
  3. Spring Framework reference: Interceptiondocs.spring.io
  4. Spring Boot reference: Error handlingdocs.spring.io
  5. Spring Framework reference: Filtersdocs.spring.io
  6. RFC 9110: Method semantics, GET/HEAD/POST and response contentrfc-editor.org
  7. Spring MVC: Request mapping and HTTP methodsdocs.spring.io
  8. Spring MVC: RequestParam arguments and type conversiondocs.spring.io
  9. Java 21 Math.addExactdocs.oracle.com
Previous
Next