Spring 的 RequestBody 和 ResponseBody 注解

概要

Spring 的 RequestBody 和 ResponseBody 注解。

博客

博客地址:IT老兵驿站

正文

关于这个问题,这里的解释非常清楚。

再参考一下代码里面的注释:

/**
 * Annotation indicating a method parameter should be bound to the body of the web request.
 * The body of the request is passed through an {@link HttpMessageConverter} to resolve the
 * method argument depending on the content type of the request. Optionally, automatic
 * validation can be applied by annotating the argument with {@code @Valid}.
 *
 * <p>Supported for annotated handler methods in Servlet environments.
 *
 * @author Arjen Poutsma
 * @since 3.0
 * @see RequestHeader
 * @see ResponseBody
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
 * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
 */

概括一下:
@RequestBody是把一个HttpRequest对象转换成一个DTO或者一个DO,这个反序列化地过程是自动完成的,而这个注解则是这个动作的开关。
现在更多的是把一个json字符串转换成一个定义好映射关系的对象。

这里会有一个默认的HttpMessageConverter,来进行转换的工作。

@ResponseBody则是反方向进行操作,把一个自定义的对象序列化成一个json字符串。

参考

https://www.baeldung.com/spring-request-response-body
https://stackoverflow.com/questions/40247556/spring-boot-automatic-json-to-object-at-controller

posted on 2019-12-15 17:06  chaiyu2002  阅读(120)  评论(0编辑  收藏  举报

导航