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 responseBootstrapping
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@RequestMappingmethodsRequestMappingHandlerAdapter— invokes themExceptionHandlerExceptionResolver— handles@ExceptionHandlerHttpEntityMethodProcessor,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 JacksonKotlinSerializationJsonHttpMessageConverter— JSON via kotlinx.serializationJaxb2RootElementHttpMessageConverter— XMLStringHttpMessageConverter,ByteArrayHttpMessageConverter,ResourceHttpMessageConverterFormHttpMessageConverter—application/x-www-form-urlencodedand multipartProtobufHttpMessageConverter— Protocol Buffers
Return value handling
HandlerMethodReturnValueHandlers convert what the controller returned into a response:
| Return type | Handler |
|---|---|
String (without @ResponseBody) |
View name → ViewResolver → View |
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:
@ExceptionHandleron the controller class — Same instance, fastest match.@ControllerAdvicebeans with@ExceptionHandler— Cross-cutting handlers.ResponseStatusExceptionResolver— Converts@ResponseStatus-annotated exceptions to status codes.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 throughReactiveAdapterRegistryand the Servlet async API.
See also
- spring-webmvc — module reference
- spring-web — shared HTTP foundation
- reactive-stack — the WebFlux alternative
- testing-support —
MockMvcfor testing controllers
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.