@ResponseBody
您可以在方法中使用 @ResponseBody
注释,让其返回值通过 HttpMessageConverter 序列化到响应主体。以下清单显示了一个示例:
You can use the @ResponseBody
annotation on a method to have the return serialized
to the response body through an
HttpMessageConverter.
The following listing shows an example:
-
Java
-
Kotlin
@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
// ...
}
@GetMapping("/accounts/{id}")
@ResponseBody
fun handle(): Account {
// ...
}
@ResponseBody
也受支持用于类级别,在这种情况下,它会被所有控制器方法继承。这是 @RestController
的效果,它只不过是一个使用 @Controller
和 @ResponseBody
进行标记的元注解。
@ResponseBody
is also supported at the class level, in which case it is inherited by
all controller methods. This is the effect of @RestController
, which is nothing more
than a meta-annotation marked with @Controller
and @ResponseBody
.
可以返回“Resource”对象以获取文件内容,将所提供的资源的 InputStream
内容复制到响应 OutputStream
中。请注意,InputStream
应该由 Resource
句柄以懒惰方式检索,以便在将它复制到响应后可靠地关闭它。如果你出于这样的目的使用 InputStreamResource
,请务必使用按需 InputStreamSource
(例如,通过检索实际 InputStream
的 lambda 表达式)对其进行构建。
A Resource
object 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
).
您可以对反应类型使用 @ResponseBody
。有关更多详细信息,请参阅 Asynchronous Requests 和 Reactive Types。
You can use @ResponseBody
with reactive types.
See Asynchronous Requests and Reactive Types for more details.
可以使用 MVC Config 的 Message Converters 选项配置或定制消息转换。
You can use the Message Converters option of the MVC Config to configure or customize message conversion.
可以将 @ResponseBody
方法与 JSON 序列化视图结合使用。有关详细信息,请参阅 Jackson JSON。
You can combine @ResponseBody
methods with JSON serialization views.
See Jackson JSON for details.