菜单

Web 技术

相关源文件

本文档概述了 Spring 框架的 Web 技术栈,包括客户端 HTTP 库及其底层基础架构。它涵盖了传统的同步和现代响应式 HTTP 客户端,以及为它们提供支持的客户端连接器实现。有关服务器端 Web 框架,请参阅 核心组件

1. Web 技术概述

Spring 框架提供了一套全面的 Web 技术,用于构建客户端和服务器端 Web 应用程序。客户端技术使应用程序能够向外部服务发出 HTTP 请求,而服务器技术则处理传入的 HTTP 请求。

来源

HTTP 抽象和 URI 处理

Spring 提供了一套丰富的 HTTP 抽象,构成了客户端和服务器端 Web 技术的基础。

HTTP 头

HttpHeaders 类通过类型安全访问器提供全面的 HTTP 头管理,支持常用头和自定义头。

主要功能

  • 通过 LinkedCaseInsensitiveMap 实现不区分大小写的头名称处理
  • 常用头(Content-Type、Accept、Authorization 等)的类型安全方法
  • 支持多值头
  • 与 Spring 类型转换系统集成
  • HTTP 日期格式化和解析

使用示例

来源

HTTP 消息实体

Spring 提供了 HttpEntity、RequestEntity 和 ResponseEntity 类来表示带有头和体的 HTTP 消息。

主要功能

  • HttpEntity:HTTP 消息表示的基类
  • RequestEntity:为客户端请求添加 HTTP 方法和 URL
  • ResponseEntity:为服务器响应添加 HTTP 状态码
  • 用于流畅 API 构建的 Builder 模式
  • 类型安全的泛型体处理

来源

URI 处理

Spring 的 URI 处理能力包括通过 UriBuilderFactory 实现的模板扩展、编码和构建。

DefaultUriBuilderFactory 提供

  • URI 模板变量扩展
  • URI 组件的正确编码
  • 基础 URL 处理
  • 查询参数管理

使用示例

来源

Spring MVC

Spring MVC 是基于 Servlet API 构建的传统 Servlet Web 框架。它为构建 Web 应用程序和 REST API 提供了全面的编程模型。

MVC 架构

WebMvcConfigurationSupport 中的关键组件

  1. 处理器映射器(按顺序)

    • RouterFunctionMapping(顺序 -1):路由函数
    • RequestMappingHandlerMapping(顺序 0):@RequestMapping 方法
    • 视图控制器映射(顺序 1):直接 URL 到视图的映射
    • BeanNameUrlHandlerMapping(顺序 2):Bean 名称 URL 映射
    • 资源处理器映射(顺序 MAX_VALUE-1):静态资源
    • 默认 Servlet 映射(顺序 MAX_VALUE):回退
  2. 处理器适配器:

    • RequestMappingHandlerAdapter:处理 @RequestMapping 方法
    • HttpRequestHandlerAdapter:处理 HttpRequestHandler 实现
    • SimpleControllerHandlerAdapter:处理 Controller 接口
    • HandlerFunctionAdapter:处理路由函数
  3. 异常解析器:

    • ExceptionHandlerExceptionResolver:@ExceptionHandler 方法
    • ResponseStatusExceptionResolver:@ResponseStatus 注解
    • DefaultHandlerExceptionResolver:标准 Spring 异常

来源

Spring MVC 中的消息转换器

Spring MVC 根据类路径依赖项自动配置 HTTP 消息转换器

WebMvcConfigurationSupport 中的转换器注册逻辑包括

  • 用于文本内容的字符串转换器
  • 用于二进制内容的字节数组转换器
  • 用于文件下载的资源转换器
  • 用于表单提交和 multipart 数据的表单转换器
  • JSON 转换器(Jackson 2、Gson、JSON-B、Kotlin Serialization)
  • XML 转换器(Jackson XML、JAXB)
  • 如果存在 Rome,则为 Feed 转换器(Atom、RSS)
  • 可用时为二进制格式转换器(SMILE、CBOR、YAML)

来源

配置支持

WebMvcConfigurationSupport 提供了 Spring MVC 的主要配置

来源

WebFlux 和响应式编程

Spring WebFlux 是 Spring 5.0 中引入的响应式 Web 框架,基于响应式流构建,专为非阻塞应用程序设计。

WebFlux 架构

WebFluxConfigurationSupport 中的关键组件

  1. 处理器映射器:

    • RequestMappingHandlerMapping:@RequestMapping 方法
    • RouterFunctionMapping:函数式路由
    • SimpleUrlHandlerMapping:URL 模式映射
  2. 处理器适配器:

    • RequestMappingHandlerAdapter:处理 @RequestMapping 方法
    • HandlerFunctionAdapter:处理 HandlerFunction 实例
    • SimpleHandlerAdapter:处理 WebHandler 接口
  3. 结果处理器:

    • ResponseEntityResultHandler:ResponseEntity 和 HttpEntity
    • ResponseBodyResultHandler:@ResponseBody 方法
    • ServerResponseResultHandler:来自路由函数的 ServerResponse
    • ViewResolutionResultHandler:视图解析

来源

响应式客户端 - WebClient

WebClient 是响应式 HTTP 客户端,提供了 RestTemplate 的非阻塞替代方案

WebClient 实现中的关键类

  • DefaultWebClient:WebClient 接口的主要实现
  • DefaultWebClientBuilder:Builder 模式实现
  • DefaultRequestBodyUriSpec:请求构建实现
  • ExchangeFunction:执行 HTTP 交换
  • ClientHttpConnector:抽象 HTTP 客户端库(Reactor Netty、Jetty 等)

使用示例

来源

Functional Router Configuration

WebFlux supports functional routing through RouterFunction and HandlerFunction

来源

方法调用

Spring's method invocation system handles the calling of handler methods in both MVC and WebFlux frameworks.

Handler Method Invocation Architecture

Argument Resolution

Spring provides extensive argument resolver support for different parameter types

  1. Common resolvers:

    • @RequestParam - Query/form parameters
    • @PathVariable - URL path variables
    • @RequestBody - Request body deserialization
    • @RequestHeader - HTTP headers
    • HttpServletRequest/ServerRequest - Native request objects
  2. Reactive-specific resolvers:

    • Mono<T> and Flux<T> parameter types
    • Reactive request body handling
    • Non-blocking argument resolution
  3. Custom resolver registration:

Reactive Type Handling

The ReactiveTypeHandler enables Spring to work with various reactive types

  • Reactor types: Mono<T>, Flux<T>
  • RxJava types: Single<T>, Observable<T>, Flowable<T>
  • CompletableFuture: CompletableFuture<T>
  • Custom reactive types: Via ReactiveAdapterRegistry

Example handler method

来源

HTTP Client Technologies

While server-side frameworks handle incoming requests, Spring also provides robust client technologies for making outbound HTTP requests.

RestTemplate - Synchronous Client

RestTemplate provides a template-based approach for synchronous HTTP operations

关键方法

  • getForObject(), getForEntity() - GET requests
  • postForObject(), postForLocation() - POST requests
  • put(), delete() - PUT and DELETE requests
  • exchange() - Generic request method
  • execute() - Low-level execution with callbacks

使用示例

来源

Client vs Server Technology Comparison

方面WebClientRestTemplateSpring MVCSpring WebFlux
模型响应式同步Servlet-based响应式
多线程Non-blocking阻塞Thread-per-request事件循环
Backpressure
流式传输有限有限
性能High concurrency中等中等High concurrency

The choice between technologies depends on application requirements

  • High throughput: WebFlux + WebClient
  • Traditional apps: Spring MVC + RestTemplate
  • Mixed scenarios: Spring MVC + WebClient
  • Legacy integration: RestTemplate with existing Spring MVC

来源

Spring Framework provides two primary HTTP client technologies with different programming models

2.1 WebClient

WebClient is a modern, reactive HTTP client introduced in Spring 5.0 that provides a non-blocking, fluent API for making HTTP requests. It supports both synchronous and asynchronous operations using Reactor's Mono and Flux types.

关键组件

  • WebClient.Builder: Creates and configures WebClient instances
  • RequestHeadersSpec/RequestBodySpec: Fluent API for building requests
  • ResponseSpec: Handles response processing
  • ExchangeFilterFunction: Intercepts and transforms requests/responses
  • ExchangeFunction: Performs the actual HTTP exchange
  • ClientHttpConnector: Low-level HTTP connection implementation

使用示例

来源

2.2 RestTemplate

RestTemplate is the traditional synchronous HTTP client in Spring that follows a template method pattern. While still supported, it's being replaced by WebClient and RestClient for new applications.

关键组件

  • ClientHttpRequestFactory: Creates HTTP requests (various implementations)
  • HttpMessageConverter: Converts between Java objects and HTTP request/response bodies
  • ResponseErrorHandler: Handles HTTP errors
  • ClientHttpRequestInterceptor: Intercepts request/response flow

使用示例

来源

3. HTTP Client Connectors

The HTTP client connectors are the foundation for both WebClient and RestTemplate, providing actual HTTP connection capabilities. Spring offers multiple implementations to support different underlying HTTP client libraries.

3.1 Reactor Netty Connector

The ReactorClientHttpConnector uses Reactor Netty's HTTP client as the underlying implementation. This is the default connector used by WebClient when no specific connector is configured.

特性

  • Non-blocking I/O based on Netty
  • Support for HTTP/2
  • 连接池
  • WebSocket 支持
  • SSL/TLS support

来源

3.2 Jetty Connector

The JettyClientHttpConnector uses the Jetty HTTP client. It's an alternative to Reactor Netty when Jetty is already being used in the application.

特性

  • Integration with Jetty server
  • HTTP/2 支持
  • 连接池
  • WebSocket 支持

来源

3.3 JDK HTTP Client Connector

The JdkClientHttpConnector uses the JDK's built-in HttpClient (available since Java 11). It's useful when you want to avoid external dependencies.

特性

  • Built into the JDK
  • HTTP/2 支持
  • WebSocket 支持
  • Synchronous and asynchronous APIs

来源

3.4 Apache HttpComponents 连接器

HttpComponentsClientHttpConnector 使用 Apache HttpComponents HttpClient。此连接器对于已使用 Apache HttpComponents 的环境很有用。

特性

  • 成熟且功能丰富
  • 广泛的配置选项
  • 强大的连接池
  • 高级身份验证支持

来源

4. HTTP 消息转换

Spring 的客户端和服务器端 Web 组件都使用 HTTP 消息转换器来转换 Java 对象与 HTTP 请求/响应正文。

关键转换器

  1. 基于文本的转换器

    • StringHttpMessageConverter:转换字符串
    • MappingJackson2HttpMessageConverter:使用 Jackson 进行 JSON 转换
    • MappingJackson2XmlHttpMessageConverter:使用 Jackson 进行 XML 转换
    • Jaxb2RootElementHttpMessageConverter:使用 JAXB 进行 XML 转换
  2. 二进制转换器

    • ByteArrayHttpMessageConverter:原始字节数组
    • ResourceHttpMessageConverter:Spring Resource 对象
  3. 表单数据转换器

    • AllEncompassingFormHttpMessageConverter:表单数据和 multipart
  4. 其他格式

    • MappingJackson2SmileHttpMessageConverter:Smile 格式(二进制 JSON)
    • MappingJackson2CborHttpMessageConverter:CBOR 格式
    • MappingJackson2YamlHttpMessageConverter:YAML 格式

转换器的自动注册在 RestTemplateWebClient 中都会发生,具体取决于类路径中可用的库。

来源

5. 使用 WebClient

WebClient 是 Spring 应用程序中推荐的 HTTP 客户端。本节介绍其主要功能和用法模式。

5.1 创建 WebClient

WebClient 实例使用构建器模式创建和配置

来源

5.2 发起请求

WebClient 为发起 HTTP 请求提供了流畅的 API

示例

  1. 简单的 GET 请求
  1. 带正文的 POST 请求
  1. 处理集合

来源

5.3 响应处理

WebClient 提供了多种处理响应的方式

  1. 使用 retrieve() 进行正文提取
  1. 使用 retrieve() 进行实体提取
  1. 使用 exchangeToMono() 以获得更多控制

来源

5.4 错误处理

WebClient 提供了几种处理错误的机制

  1. 默认错误处理
  1. 自定义状态处理程序
  1. 全局状态处理程序

来源

6. 使用 RestTemplate

尽管 WebClient 是新应用程序的首选 HTTP 客户端,但 RestTemplate 仍广泛用于现有应用程序。

6.1 创建 RestTemplate

创建和配置 RestTemplate

来源

6.2 使用 RestTemplate 发起请求

RestTemplate 为每种 HTTP 方法提供了特定的方法

来源

7. WebClient 与 RestTemplate 对比

以下是两种主要 HTTP 客户端技术的比较

功能WebClientRestTemplate
编程模型响应式(非阻塞)同步(阻塞)
返回值类型Mono/Flux直接对象
API 风格流畅的链式 API模板方法模式
HTTP 方法统一 API(method() 调用)针对不同 HTTP verb 的专用方法
反压支持是(通过 Reactor)
错误处理onStatus() + 响应式操作符ResponseErrorHandler 接口
过滤器/拦截器ExchangeFilterFunctionClientHttpRequestInterceptor
资源效率对大量连接高效每个请求一个线程(对大量连接效率低下)
Java 版本Java 8+Java 8+
服务器支持可与任何 HTTP 服务器配合使用可与任何 HTTP 服务器配合使用

何时选择哪个客户端

  • 当需要以下情况时,请使用 WebClient

    • 构建响应式应用程序
    • 需要非阻塞操作
    • 处理流式数据
    • 管理大量并发连接
    • 构建新应用程序
  • 当满足以下条件时,请使用 RestTemplate

    • 维护已在使用它的现有应用程序
    • 简单的同步操作已足够
    • 不需要响应式编程

来源

8. 未来方向

Spring Framework 的 Web 技术栈仍在不断发展

  1. WebClient 是所有新应用程序推荐使用的 HTTP 客户端
  2. Spring Framework 6.1 中引入了 RestClient,作为 RestTemplate 的现代化替代品,它具有流畅的 API,但仍然是同步操作
  3. RestTemplate 仍处于维护模式,未计划添加新功能
  4. HTTP/2 和 HTTP/3 支持在底层客户端连接器中持续改进
  5. WebFlux 和 WebClient 的响应式编程模型是 Spring Web 技术栈的战略方向

随着 Spring Framework 的不断发展,重点越来越放在响应式编程模型和对现代 HTTP 协议版本支持上,同时保持对现有应用程序的向后兼容性。

来源