skip to content

Request-Processing Lifecycle

What actually happens between the servlet container and your controller method: the front controller, handler mapping, handler adapters, exception resolvers and view resolution. Interviewers ask you to trace a request end to end, and this is the trace.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

explore

questions

25

When a Spring MVC controller throws an exception, how does the framework turn it into an HTTP response?

level: juniorimportance: must knowfreq 45%

answer

  1. DispatcherServlet.processHandlerException
  2. loop resolvers until non-null ModelAndView
  3. empty ModelAndView = handled, no view
  4. null everywhere → rethrow → /error
  5. 3 defaults in fixed order

basics

~20 s

The DispatcherServlet catches the exception and offers it to a list of HandlerExceptionResolvers. The first one that can handle it writes the response (status and body). If none handle it, the exception propagates to the servlet container.

solid answer

~30 s

When a handler (or interceptor) throws, DispatcherServlet does not let the exception escape immediately. It calls processHandlerException, which loops over its ordered list of HandlerExceptionResolver beans, invoking resolveException(request, response, handler, ex) on each. The first resolver that returns a non-null ModelAndView wins and the loop stops; an empty ModelAndView means 'handled, response already written.' If every resolver returns null, the original exception is rethrown and bubbles up to the servlet container, which in Spring Boot triggers an ERROR dispatch to /error (BasicErrorController). By default Spring registers three resolvers: ExceptionHandlerExceptionResolver, ResponseStatusExceptionResolver, and DefaultHandlerExceptionResolver, tried in that order.

code

java · 23 lines
java
// The strategy DispatcherServlet iterates over:
public interface HandlerExceptionResolver {
    // null  -> not my job, try next resolver
    // ModelAndView (possibly empty) -> handled
    ModelAndView resolveException(HttpServletRequest request,
                                  HttpServletResponse response,
                                  Object handler,
                                  Exception ex);
}

// A minimal custom resolver:
public class TeapotResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest req,
                                         HttpServletResponse res,
                                         Object handler, Exception ex) {
        if (ex instanceof CoffeeRequestedException) {
            res.setStatus(418); // I'm a teapot
            return new ModelAndView(); // empty = response handled
        }
        return null; // let the next resolver try
    }
}

go deeper

for a junior

Know that DispatcherServlet delegates to a list of HandlerExceptionResolvers and the first that handles it wins.

for a middle

Name the three default resolvers and the null-vs-ModelAndView contract.

for a senior

Explain the fall-through to /error and the boundary (filters/committed responses are outside the chain).

for a principal

Discuss how this SPI unifies every error mechanism and how to extend it without breaking defaults.

## The problem A `@Controller` method can throw any exception. Something has to convert that thrown `Throwable` into a proper HTTP response (a status code, headers, and optionally a body). In Spring MVC that job belongs to the **HandlerExceptionResolver** strategy. ## HandlerExceptionResolver — the SPI It is a single-method interface: ```java public interface HandlerExceptionResolver { ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); } ``` - Return **null** = "I don't handle this exception, try the next resolver." - Return a **non-null ModelAndView** = "handled." An *empty* ModelAndView (`mav.isEmpty()` / `mav.clearEmptyRequest`) signals the response has already been fully written (e.g., status set directly), so no view needs rendering. ## Where it plugs in — DispatcherServlet `DispatcherServlet.doDispatch()` wraps handler mapping and handler execution in a try/catch. A caught `Exception` is stored, and `processDispatchResult(...)` calls `processHandlerException(request, response, handler, ex)`. That method iterates `this.handlerExceptionResolvers` (a `List<HandlerExceptionResolver>`), calling `resolveException` on each **in order** until one returns non-null. That first non-null result short-circuits the loop. ## The default chain When you use `@EnableWebMvc` or Spring Boot's autoconfiguration, `WebMvcConfigurationSupport` registers three resolvers, tried in this order: 1. **ExceptionHandlerExceptionResolver** — dispatches to your `@ExceptionHandler` methods (in controllers or `@ControllerAdvice`). 2. **ResponseStatusExceptionResolver** — handles exceptions carrying `@ResponseStatus` and `ResponseStatusException`. 3. **DefaultHandlerExceptionResolver** — maps Spring MVC's own built-in exceptions (e.g., 405, 415, 400) to status codes. ## What if nobody handles it? If all three return null, `processHandlerException` **rethrows** the exception. It leaves DispatcherServlet, goes to any Filters, then to the servlet container. In Spring Boot the container performs an internal ERROR dispatch to `/error`, served by `BasicErrorController`, producing the default JSON/Whitelabel error page. ## Key gotchas - The chain only sees exceptions thrown **inside** DispatcherServlet's dispatch (handler mapping, interceptors, handler execution). Exceptions from **Filters** run *before* DispatcherServlet and are never seen by these resolvers. - Once the response is **committed** (bytes flushed), a resolver can no longer change status — you may get a truncated/garbled response. ## When to care Every Spring MVC error-handling feature — `@ExceptionHandler`, `@ResponseStatus`, `ResponseStatusException`, the automatic 405/415 responses — is just a resolver in this chain. Understanding the chain explains *why* one mechanism wins over another.

  • What is the difference between a resolver returning null and returning an empty ModelAndView?
    null means 'I did not handle this — try the next resolver.' An empty ModelAndView means 'handled; I already wrote the response (e.g., set the status), so DispatcherServlet should not render any view.' A populated ModelAndView means 'handled — render this view/model.'
  • If no resolver handles the exception, where does it go?
    It is rethrown out of DispatcherServlet, passes back through the filter chain, and reaches the servlet container, which triggers an ERROR dispatch. In Spring Boot that lands on BasicErrorController at /error.

saying these in an interview costs you the question

  • Thinking the exception is caught by a try/catch in the controller framework and swallowed silently
  • Believing @ExceptionHandler is a special language feature rather than one resolver in a chain
  • Assuming exceptions thrown in a Servlet Filter are handled by these resolvers

context

open as a page

What is a HandlerAdapter in Spring MVC and why does DispatcherServlet need one?

level: juniorimportance: must knowfreq 55%

basics

~10 s

A HandlerAdapter knows how to actually call a handler. DispatcherServlet finds the handler, then delegates to a HandlerAdapter to invoke it and get a ModelAndView, so it doesn't need to know each handler type.

open as a page

What is a HandlerMapping in Spring MVC, and what does its getHandler method return for an incoming request?

level: juniorimportance: must knowfreq 70%

basics

~10 s

A HandlerMapping decides which controller method should handle an incoming HTTP request. Its getHandler method takes the request and returns a HandlerExecutionChain: the chosen handler plus any interceptors that run around it.

open as a page

What is the DispatcherServlet in Spring MVC, and what design pattern does it implement?

level: juniorimportance: must knowfreq 80%

basics

~10 s

DispatcherServlet is Spring MVC's single entry point for HTTP requests. It implements the Front Controller pattern: one servlet receives every request and delegates to the right handler (controller), then renders the response.

open as a page

In Spring MVC, when a controller method returns the String "home", how does that turn into an actual HTML page? Walk through logical view names, the Model, and the ViewResolver.

level: juniorimportance: must knowfreq 70%

basics

~10 s

The returned String is a logical view name, not a file path. A ViewResolver maps it to a real template (e.g. "home" -> /WEB-INF/home.jsp or home.html). Data reaches the view through a Model object.

open as a page

What are the three default HandlerExceptionResolvers Spring MVC registers, and what does each one handle?

level: middleimportance: must knowfreq 40%

basics

~10 s

ExceptionHandlerExceptionResolver (invokes @ExceptionHandler methods), ResponseStatusExceptionResolver (handles @ResponseStatus-annotated exceptions and ResponseStatusException), and DefaultHandlerExceptionResolver (maps Spring MVC's own exceptions like 405/415/400 to status codes). They run in that order.

open as a page

Walk through what RequestMappingHandlerAdapter.invokeHandlerMethod does when a @RequestMapping method is called.

level: middleimportance: must knowfreq 45%

basics

~20 s

It wraps the controller method in a ServletInvocableHandlerMethod, plugs in the argument resolvers and return-value handlers, binds a ModelAndViewContainer, resolves each parameter, invokes the method, and hands the return value to the right return-value handler.

open as a page

How does RequestMappingHandlerMapping build and use its RequestMappingInfo registry to match a request to a controller method?

level: middleimportance: must knowfreq 60%

basics

~20 s

At startup it scans all @Controller beans, turns each @RequestMapping method into a RequestMappingInfo (path, HTTP method, params, headers, consumes, produces) and stores them in a registry. Per request it finds the RequestMappingInfos that match, picks the most specific one, and returns that HandlerMethod.

open as a page

Walk through the doDispatch() flow: what happens inside DispatcherServlet when a request arrives?

level: middleimportance: must knowfreq 72%

basics

~10 s

doDispatch finds a handler via HandlerMapping, gets a HandlerAdapter, runs interceptor preHandle, invokes the handler to get a ModelAndView, runs postHandle, then renders the view (or writes the body) and runs afterCompletion.

open as a page

Explain the "redirect:" and "forward:" prefixes on a view name. How do they differ, and how do you carry data across a redirect without exposing it as query params?

level: middleimportance: must knowfreq 65%

basics

~10 s

"redirect:/x" sends a 302 telling the browser to request /x again (new request). "forward:/x" hands off server-side to another handler in the same request. To pass data over a redirect safely, use RedirectAttributes.addFlashAttribute.

open as a page

Compare InternalResourceViewResolver (JSP) with ThymeleafViewResolver. How does Spring Boot auto-configure Thymeleaf, and why is Thymeleaf preferred for modern server-side rendering?

level: middleimportance: should knowfreq 45%

basics

~20 s

InternalResourceViewResolver resolves names to JSPs via a servlet forward (prefix/suffix, files under /WEB-INF). ThymeleafViewResolver resolves them to .html templates in classpath:/templates rendered by the Thymeleaf engine. Boot auto-configures Thymeleaf when the starter is on the classpath.

open as a page

Explain what DefaultHandlerExceptionResolver and ResponseStatusExceptionResolver do, including the body/status subtleties.

level: seniorimportance: should knowfreq 26%

basics

~20 s

DefaultHandlerExceptionResolver maps Spring MVC's built-in exceptions (like 405, 415, 400) to status codes. ResponseStatusExceptionResolver applies the status from @ResponseStatus-annotated exceptions or a ResponseStatusException. Both mainly set the status; they don't produce a custom response body.

open as a page

How is the order of HandlerExceptionResolvers determined, and what happens if you register your own resolver?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Resolvers are sorted by their Ordered value and tried lowest-order-first; the first non-null result wins. The three defaults are ExceptionHandlerExceptionResolver (0), ResponseStatusExceptionResolver (1), DefaultHandlerExceptionResolver (lowest precedence). Use extendHandlerExceptionResolvers to add yours while keeping the defaults.

open as a page

How do HandlerMethodArgumentResolver and HandlerMethodReturnValueHandler work, and how does the adapter pick the right one?

level: seniorimportance: should knowfreq 40%

basics

~20 s

For each parameter the adapter asks every argument resolver supportsParameter; the first match resolves the value. For the return value it asks every return-value handler supportsReturnType; the first match writes the response or sets the view. Both are strategy lists tried in order.

open as a page

For a @RestController method returning a DTO, why does HandlerAdapter.handle ultimately return a null ModelAndView, and where is the JSON actually written?

level: seniorimportance: should knowfreq 30%

basics

~10 s

@ResponseBody sends the return value to RequestResponseBodyMethodProcessor, which serializes it with an HttpMessageConverter and marks the request as handled. Because the response is already written, no view is needed, so getModelAndView returns null.

open as a page

What is a HandlerExecutionChain, and how do the HandlerInterceptor callbacks it carries execute around the handler — including when a request is short-circuited?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A HandlerExecutionChain pairs the chosen handler with the interceptors that apply to the request. The DispatcherServlet runs each interceptor's preHandle before the handler, postHandle after it (before view rendering), and afterCompletion at the very end. If a preHandle returns false, the request is stopped early.

open as a page

Multiple HandlerMapping beans exist in a Spring MVC app. In what order are they consulted, and how do RequestMappingHandlerMapping and BeanNameUrlHandlerMapping fit into that ordering?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The DispatcherServlet keeps all HandlerMapping beans sorted by their Ordered value (lowest first) and asks each in turn until one returns a non-null chain. RequestMappingHandlerMapping is ordered before BeanNameUrlHandlerMapping, so annotated controllers win over URL-named beans.

open as a page

Explain the WebApplicationContext hierarchy in a DispatcherServlet setup: root context vs. servlet context.

level: seniorimportance: should knowfreq 48%

basics

~20 s

Classic Spring MVC has two contexts: a root WebApplicationContext (services, repositories, shared beans) loaded by ContextLoaderListener, and a child servlet context per DispatcherServlet (controllers, MVC beans). The child sees the parent's beans, not vice versa.

open as a page

What does initStrategies() do, and how does DispatcherServlet discover its special beans at startup?

level: seniorimportance: should knowfreq 55%

basics

~10 s

On context refresh, initStrategies() populates DispatcherServlet's strategy beans (HandlerMappings, HandlerAdapters, ViewResolvers, resolvers, etc.) by looking them up from the WebApplicationContext, falling back to defaults in DispatcherServlet.properties if none are defined.

open as a page

What is ContentNegotiatingViewResolver and how does it decide which view to render? Explain content negotiation via Accept header vs path extension vs request parameter.

level: seniorimportance: should knowfreq 35%

basics

~20 s

It's a ViewResolver that picks a view based on the requested media type (content negotiation). It determines the desired MIME type (from Accept header, URL extension, or a request param), then delegates to other ViewResolvers/Views and returns the one matching that media type.

open as a page

How does Spring Boot register and configure the DispatcherServlet? Walk through DispatcherServletAutoConfiguration.

level: principalimportance: should knowfreq 40%

basics

~10 s

Spring Boot's DispatcherServletAutoConfiguration creates the DispatcherServlet bean and a DispatcherServletRegistrationBean that registers it with the embedded servlet container, mapped to spring.mvc.servlet.path (default '/'), using the single Boot application context.

open as a page

You configure multiple ViewResolvers in one application. Explain how DispatcherServlet walks the resolver chain, the role of Ordered/order, and the classic pitfall with InternalResourceViewResolver in a mixed chain.

level: principalimportance: should knowfreq 25%

basics

~20 s

DispatcherServlet holds an ordered list of ViewResolvers and calls each in order until one returns a non-null View. Order comes from the Ordered interface / order property. InternalResourceViewResolver always returns a View (never null), so it must be last or it shadows the others.

open as a page

What exceptions can the HandlerExceptionResolver chain NOT handle, and what are the key edge cases (filters, committed responses, view rendering, async)?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

The chain only handles exceptions thrown inside DispatcherServlet's dispatch (handler mapping, interceptors, handler execution). It cannot handle exceptions from Servlet Filters (they run before DispatcherServlet), from view rendering after the response is committed, or after the response is already flushed. Those fall to the container's error page.

open as a page

How does RequestMappingHandlerAdapter handle async return types (Callable, DeferredResult), and why is the HandlerAdapter abstraction valuable architecturally?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

For async return types the adapter starts async processing via WebAsyncManager, returns a null ModelAndView, and lets the servlet container release the thread. When the result is ready the request is re-dispatched and only the return-value handling re-runs. The abstraction keeps DispatcherServlet closed to modification but open to new handler types.

open as a page

You need to route requests to different controller methods based on a custom rule (e.g. an API version header) that plain @RequestMapping can't express. How would you extend the HandlerMapping / RequestMappingInfo machinery to do this cleanly?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Subclass RequestMappingHandlerMapping and override getCustomTypeCondition/getCustomMethodCondition to attach your own RequestCondition (e.g. one that matches an API-Version header). Spring folds it into each RequestMappingInfo, so it participates in matching and specificity ranking alongside the built-in conditions.

open as a page