ResponseEntity

ResponseEntity 就像 @ResponseBody 一样,但带有状态和标题。例如:

ResponseEntity is like @ResponseBody but with status and headers. For example:

  • Java

  • Kotlin

@GetMapping("/something")
public ResponseEntity<String> handle() {
	String body = ... ;
	String etag = ... ;
	return ResponseEntity.ok().eTag(etag).body(body);
}
@GetMapping("/something")
fun handle(): ResponseEntity<String> {
	val body: String = ...
	val etag: String = ...
	return ResponseEntity.ok().eTag(etag).build(body)
}

WebFlux 支持使用单个值 reactive type 来异步生成 ResponseEntity,和/或主体的单值和多值响应类型。这允许通过 ResponseEntity 产生多种异步响应,如下所示:

WebFlux supports using a single value reactive type to produce the ResponseEntity asynchronously, and/or single and multi-value reactive types for the body. This allows a variety of async responses with ResponseEntity as follows:

  • ResponseEntity&lt;Mono&lt;T&gt;&gt;`或 `ResponseEntity&lt;Flux&lt;T&gt;&gt;`使响应状态和标题在稍后的某个时刻以异步方式提供时立即为人所知。如果 body 由 0..1 值组成,则使用 `Mono;如果它可以产生多个值,则使用 Flux

  • ResponseEntity<Mono<T>> or ResponseEntity<Flux<T>> make the response status and headers known immediately while the body is provided asynchronously at a later point. Use Mono if the body consists of 0..1 values or Flux if it can produce multiple values.

  • `Mono&lt;ResponseEntity&lt;T&gt;&gt;`稍后以异步方式提供所有三个内容 — 响应状态、标题和 body。这允许响应状态和标题根据异步请求处理的结果而有所不同。

  • Mono<ResponseEntity<T>> provides all three — response status, headers, and body, asynchronously at a later point. This allows the response status and headers to vary depending on the outcome of asynchronous request handling.

  • `Mono&lt;ResponseEntity&lt;Mono&lt;T&gt;&gt;&gt;`或`Mono&lt;ResponseEntity&lt;Flux&lt;T&gt;&gt;&gt;`是另一种可能的备选方案,尽管不太常见。它们先异步提供响应状态和标头,然后异步提供响应体,再异步地提供响应体。

  • Mono<ResponseEntity<Mono<T>>> or Mono<ResponseEntity<Flux<T>>> are yet another possible, albeit less common alternative. They provide the response status and headers asynchronously first and then the response body, also asynchronously, second.