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 = ...
	val etag = ...
	return ResponseEntity.ok().eTag(etag).build(body)
}

正文通常会作为值对象提供,以便由其中一种已注册的 HttpMessageConverters 呈现为相应的响应表示(如 JSON)。

The body will usually be provided as a value object to be rendered to a corresponding response representation (e.g. JSON) by one of the registered HttpMessageConverters.

对于文件内容,可以通过复制已提供资源的 InputStream 内容到响应 OutputStream,来返回 ResponseEntity<Resource>。请注意,InputStream 应由 Resource 句柄以延迟方式检索,以便在复制到响应之后可靠地将其关闭。如果出于此目的使用 InputStreamResource,请务必使用按需 InputStreamSource 来构建它(例如,通过检索实际 InputStream 的 lambda 表达式)。此外,仅当结合使用自定义的 contentLength() 实现时才支持 InputStreamResource 的自定义子类,这种实现避免为此目的消耗流。

A ResponseEntity<Resource> can be returned for file content, copying the InputStream content of the provided resource to the response OutputStream. Note that the InputStream should be lazily retrieved by the Resource handle in order to reliably close it after it has been copied to the response. If you are using InputStreamResource for such a purpose, make sure to construct it with an on-demand InputStreamSource (e.g. through a lambda expression that retrieves the actual InputStream). Also, custom subclasses of InputStreamResource are only supported in combination with a custom contentLength() implementation which avoids consuming the stream for that purpose.

Spring MVC 支持使用一个值 reactive type 异步生成 ResponseEntity,和/或单个和多值的响应主体反应类型。这允许使用以下类型的异步响应:

Spring MVC 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 the following types of async responses:

  • 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<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.