Open-Source Wikis

/

Spring Framework

/

Features

/

Web MVC

spring-projects/spring-framework

Web MVC

Active contributors: rstoyanchev, Juergen Hoeller, Brian Clozel

Spring MVC — the Servlet-based, imperative web stack — is delivered by spring-webmvc, built on top of spring-web and spring-context. This page provides a top-down view of how an HTTP request becomes a response.

End-to-end request lifecycle

sequenceDiagram
    participant Client
    participant Servlet as Servlet container
    participant Filters as Servlet filters
    participant DS as DispatcherServlet
    participant HM as HandlerMapping
    participant HA as HandlerAdapter
    participant Inter as HandlerInterceptors
    participant Args as ArgumentResolvers
    participant Ctrl as Controller
    participant Conv as HttpMessageConverters
    participant View as ViewResolver / View
    participant ER as ExceptionResolver

    Client->>Servlet: HTTP request
    Servlet->>Filters: doFilter
    Filters->>DS: service(req, res)
    DS->>HM: getHandler
    HM-->>DS: HandlerExecutionChain (handler + interceptors)
    DS->>Inter: preHandle
    Inter-->>DS: ok
    DS->>HA: handle
    HA->>Args: resolve method args
    Args->>Conv: deserialize @RequestBody (JSON, XML, …)
    Conv-->>Args: object
    Args-->>HA: arg array
    HA->>Ctrl: invoke method
    alt success
        Ctrl-->>HA: object / ResponseEntity / view name
        HA->>Conv: serialize response body (if @ResponseBody)
        HA-->>DS: ModelAndView (or null)
        DS->>Inter: postHandle
        opt has view name
            DS->>View: resolve + render(model)
        end
    else exception
        Ctrl-->>HA: throws
        HA-->>DS: exception
        DS->>ER: try @ExceptionHandler / @ControllerAdvice
        ER-->>DS: ModelAndView
    end
    DS->>Inter: afterCompletion
    DS-->>Servlet: response
    Servlet-->>Client: HTTP response

Bootstrapping

In a Spring Boot application, DispatcherServlet is registered automatically. In a plain Spring app, you register it via WebApplicationInitializer (servlet 5+) or web.xml. The dispatcher's own ApplicationContext is the web context, typically a child of a root ApplicationContext.

@EnableWebMvc (or implementing WebMvcConfigurer) imports the default beans:

  • RequestMappingHandlerMapping — discovers @RequestMapping methods
  • RequestMappingHandlerAdapter — invokes them
  • ExceptionHandlerExceptionResolver — handles @ExceptionHandler
  • HttpEntityMethodProcessor, RequestResponseBodyMethodProcessor — body conversion
  • Default HttpMessageConverters (Jackson, Jaxb, etc.) based on what's on the classpath

Spring Boot adds extra defaults on top (auto-configured Jackson modules, error pages, static resources, etc.).

@RequestMapping matching

A request comes in. RequestMappingHandlerMapping walks every registered controller method and asks: "Does this match?" Matching combines a stack of RequestConditions:

Condition Source
Path @RequestMapping(value=…) or @GetMapping("…")
Method @GetMapping, @PostMapping, etc.
Params @RequestMapping(params=…)
Headers @RequestMapping(headers=…)
Consumes @RequestMapping(consumes=…)
Produces @RequestMapping(produces=…)

Matches are ranked: more specific patterns win, then by HTTP method, etc. The implementation lives in org.springframework.web.servlet.mvc.condition.

Argument resolution

A method's parameters are resolved by chained HandlerMethodArgumentResolvers. Common ones:

Resolver Triggers
PathVariableMethodArgumentResolver @PathVariable Long id
RequestParamMethodArgumentResolver @RequestParam String q and missing-annotation primitives
RequestHeaderMethodArgumentResolver @RequestHeader("...") String h
RequestBodyMethodArgumentResolver @RequestBody Foo body
ModelAttributeMethodArgumentResolver @ModelAttribute Foo foo
RequestPartMethodArgumentResolver @RequestPart Foo part (multipart)
ServletRequestMethodArgumentResolver HttpServletRequest, Locale, Principal, …

Custom resolvers register via WebMvcConfigurer.addArgumentResolvers.

Body conversion (HttpMessageConverter)

HttpMessageConverter<T> converts request bodies to objects (@RequestBody) and objects to response bodies (@ResponseBody, @RestController). Spring picks one based on the request's Content-Type and the method parameter type, or based on the response's negotiated content type.

Built-in converters (depending on classpath):

  • MappingJackson2HttpMessageConverter — JSON via Jackson
  • KotlinSerializationJsonHttpMessageConverter — JSON via kotlinx.serialization
  • Jaxb2RootElementHttpMessageConverter — XML
  • StringHttpMessageConverter, ByteArrayHttpMessageConverter, ResourceHttpMessageConverter
  • FormHttpMessageConverterapplication/x-www-form-urlencoded and multipart
  • ProtobufHttpMessageConverter — Protocol Buffers

Return value handling

HandlerMethodReturnValueHandlers convert what the controller returned into a response:

Return type Handler
String (without @ResponseBody) View name → ViewResolverView
ModelAndView Same
ResponseEntity<T> Status + headers + body (via converter)
@ResponseBody Object Body via converter
void + HttpServletResponse argument Direct response writing
DeferredResult<T> / Callable<T> Async (Servlet 3 async)
Mono<T> / Flux<T> Reactive streaming via ReactiveAdapterRegistry

Exception handling

In order:

  1. @ExceptionHandler on the controller class — Same instance, fastest match.
  2. @ControllerAdvice beans with @ExceptionHandler — Cross-cutting handlers.
  3. ResponseStatusExceptionResolver — Converts @ResponseStatus-annotated exceptions to status codes.
  4. DefaultHandlerExceptionResolver — Built-in handling of framework exceptions (e.g., MethodArgumentNotValidException → 400).

ResponseEntityExceptionHandler is a base class that gives you typed handlers for every framework exception. Most apps subclass it to centralize error responses.

Functional endpoints

Alongside @Controller, Spring MVC supports a functional API:

@Bean
RouterFunction<ServerResponse> routes(UserHandler h) {
    return route(GET("/users/{id}"), h::get)
       .andRoute(POST("/users"), h::create);
}

This produces the same wire behavior as annotation-driven controllers; it's wired through RouterFunctionMapping and HandlerFunctionAdapter.

Static resources

ResourceHandlerRegistry (WebMvcConfigurer.addResourceHandlers) maps URL prefixes to classpath/file directories. The framework supports versioning, ETag generation, and content encoding for static assets.

Async patterns

Spring MVC supports two async paradigms:

  • DeferredResult<T> / Callable<T> — Servlet 3 async dispatch. Return immediately, complete the response later from another thread.
  • Reactive return types — Returning Mono<T>/Flux<T> from an MVC controller works (since Spring 5) by adapting through ReactiveAdapterRegistry and the Servlet async API.

See also

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Web MVC – Spring Framework wiki | Factory