Spring's web infrastructure provides the foundational HTTP abstractions and client capabilities shared by both servlet-based (spring-webmvc) and reactive (spring-webflux) web frameworks. The spring-web module defines core HTTP types, message conversion, and HTTP client implementations, while both spring-webmvc and spring-webflux build framework-specific request handling and configuration on top of these abstractions.
Web Infrastructure Layer Architecture
The spring-web module provides:
HttpHeaders, MediaType, RequestEntity, ResponseEntity for representing HTTP messagesUriComponentsBuilder and UriBuilderFactory for constructing and templating URIsHttpMessageConverter infrastructure for serializing/deserializing HTTP bodiesRestTemplate for blocking HTTP operationsInvocableHandlerMethod base classes for invoking controller methodsThe spring-webflux module adds reactive capabilities:
WebClient and DefaultWebClient for non-blocking HTTP operationsClientResponse and DefaultClientResponse for processing responsesBoth spring-webmvc and spring-webflux build on this infrastructure to provide framework-specific request mapping (RequestMappingHandlerMapping), handler adaptation (RequestMappingHandlerAdapter), and configuration support (WebMvcConfigurationSupport, WebFluxConfigurationSupport).
Sources:
The spring-web module provides core HTTP abstractions for representing requests and responses. These types are used by both HTTP clients (RestTemplate, WebClient) and server-side frameworks (spring-webmvc, spring-webflux).
HTTP Message Type Hierarchy
HttpHeaders - Case-insensitive multi-value map for HTTP headers:
LinkedCaseInsensitiveMap for case-insensitive key lookupsgetContentType(), getAccept(), getContentLength()ReadOnlyHttpHeadersMediaType - Represents MIME types with quality parameters:
MimeType with support for HTTP quality (q) parametersAPPLICATION_JSON, TEXT_HTML, MULTIPART_FORM_DATAAccept and Content-Type headersRequestEntity - Represents HTTP request with method, URI, headers, and body:
RestTemplate.exchange() for full request controlRequestEntity.post(uri).header(name, value).body(object)ResponseEntity - Represents HTTP response with status, headers, and body:
@Controller methods in Spring MVC/WebFluxRestTemplate and WebClient methodsResponseEntity.ok().header(name, value).body(object)See page 4.1 for detailed coverage of HTTP abstractions including LinkedCaseInsensitiveMap implementation, MimeType parsing, and MultiValueMap utilities.
Sources:
Spring provides UriComponentsBuilder and UriBuilderFactory for constructing URIs with variable expansion and encoding. These are used extensively by HTTP clients (RestTemplate, WebClient) and by handler mappings for generating URIs.
URI Building Infrastructure
UriComponentsBuilder - Fluent API for building URIs:
"/users/{id}" with Map.of("id", 123)DefaultUriBuilderFactory - Factory implementation with defaults:
TEMPLATE_AND_VALUES, VALUES_ONLY, URI_COMPONENTRestTemplate and WebClient to construct request URIsEncoding Modes:
| Mode | Description | Use Case |
|---|---|---|
TEMPLATE_AND_VALUES | Encode template and expanded values separately | General purpose (recommended) |
VALUES_ONLY | Only encode expanded values, not template | Pre-encoded templates |
URI_COMPONENT | Encode all URI components | Legacy compatibility |
Example usage:
See page 4.2 for detailed coverage of URI building including encoding strategies, RFC vs WhatWG parsing modes, and integration with HTTP clients.
Sources:
RestTemplate is Spring's synchronous, blocking HTTP client providing template methods for common HTTP operations. While still in maintenance mode, it remains widely used in existing applications.
RestTemplate Architecture
Template Methods - Convenience methods for HTTP operations:
getForObject(), getForEntity() - GET requestspostForLocation(), postForObject(), postForEntity() - POST requestsput() - PUT requestsdelete() - DELETE requestsexchange() - Generic method for any HTTP operationMessage Conversion - HttpMessageConverter infrastructure:
Content-Type and Accept headerssetMessageConverters()Request Interception - ClientHttpRequestInterceptor chain:
setInterceptors()Error Handling - ResponseErrorHandler interface:
DefaultResponseErrorHandler throws exceptions for 4xx/5xxsetErrorHandler()RestClientException subclassesObservation Support - Micrometer integration:
setObservationRegistry()setObservationConvention()See page 4.3 for detailed coverage of RestTemplate including request execution flow, RequestCallback, ResponseExtractor, and observation integration.
Sources:
WebClient is Spring's non-blocking, reactive HTTP client built on Project Reactor. It provides a fluent API for constructing HTTP requests and processing responses asynchronously.
WebClient Request Processing Flow
WebClient - Main interface with fluent API:
get(), post(), put(), delete(), patch()RequestHeadersUriSpec and RequestBodyUriSpecretrieve() or exchangeToMono()/exchangeToFlux()DefaultWebClient - Default implementation:
ExchangeFunction, UriBuilderFactory, default headers/cookiesClientRequest from request specObservationRegistry for metricsExchangeFunction - Core exchange abstraction:
exchange(ClientRequest) returns Mono<ClientResponse>ClientHttpConnectorExchangeFilterFunctionClientHttpConnector - HTTP client abstraction:
ReactorClientHttpConnector, JettyClientHttpConnector, JdkClientHttpConnector, HttpComponentsClientHttpConnectorconnect() returns Mono<ClientHttpResponse>ClientResponse - Response representation:
statusCode(), headers(), cookies()bodyToMono(), bodyToFlux(), body(BodyExtractor)createException() for 4xx/5xx responsesDefaultClientResponse - Default response implementation:
ClientHttpResponse from connectorExchangeStrategies for body decoding via HttpMessageReaderExample usage:
See page 4.4 for detailed coverage of WebClient including builder configuration, filter chains, error handling strategies, and observation integration.
Sources:
WebClient is the recommended HTTP client in Spring applications. This section covers its key features and usage patterns.
WebClient instances are created and configured using a builder pattern:
Sources:
WebClient provides a fluent API for making HTTP requests:
Examples:
Sources:
WebClient offers several ways to handle responses:
retrieve() with body extraction:retrieve() with entity extraction:exchangeToMono() for more control:Sources:
WebClient provides several mechanisms for handling errors:
Sources:
Although WebClient is the preferred HTTP client for new applications, RestTemplate is still widely used in existing applications.
Creating and configuring a RestTemplate:
Sources:
RestTemplate provides specific methods for each HTTP method:
Sources:
Here's a comparison of the two main HTTP client technologies:
| Feature | WebClient | RestTemplate |
|---|---|---|
| Programming model | Reactive (non-blocking) | Synchronous (blocking) |
| Return types | Mono/Flux | Direct objects |
| API style | Fluent, chained API | Template method pattern |
| HTTP methods | Unified API (method() call) | Specific methods per HTTP verb |
| Backpressure support | Yes (via Reactor) | No |
| Error handling | onStatus() + reactive operators | ResponseErrorHandler interface |
| Filters/Interceptors | ExchangeFilterFunction | ClientHttpRequestInterceptor |
| Resource efficiency | Efficient with many connections | Thread per request (inefficient for many connections) |
| Java version | Java 8+ | Java 8+ |
| Server support | Works with any HTTP server | Works with any HTTP server |
Use WebClient when:
Use RestTemplate when:
Sources:
Spring Framework's web technology stack continues to evolve:
WebClient is the recommended HTTP client for all new applicationsRestClient was introduced in Spring Framework 6.1 as a modern replacement for RestTemplate with a fluent API but still synchronous operationRestTemplate remains in maintenance mode, with no new features plannedAs the Spring Framework evolves, the focus is increasingly on reactive programming models and support for modern HTTP protocol versions, while maintaining backward compatibility with existing applications.
Sources:
Refresh this wiki