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 对象,这个反序列化地过程是自动完成的(由 HttpMessageConverter 完成),而这个注解则是这个动作的开关。
现在更多的是把一个 json 字符串转换成一个定义好映射关系的对象。

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

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

这里其实并没有说这两个注解只针对 json,但是通过实践发现,这两个注解好像只能是针对 json 来操作,x-www-form-urlencoded 的名值对格式似乎是不支持的,关于这一点,参考:https://stackoverflow.com/questions/33796218/content-type-application-x-www-form-urlencodedcharset-utf-8-not-supported-for 这个帖子,这块还需要再深入研究一下。

但是参考官网,却一个字都没有说不支持表单格式。

参考:https://stackoverflow.com/questions/51008382/why-spring-boot-application-doesnt-require-enablewebmvc/51008465 和 https://stackoverflow.com/questions/51008382/why-spring-boot-application-doesnt-require-enablewebmvc, 这里说的是使用了 “@SpringBootApplication” 就不需要使用 “@EnableWebMvc” ,这个问题还是有些说不通。

又参考了[这篇|https://dzone.com/articles/spring-boot-enablewebmvc-and-common-use-cases]帖子,这里说 SpringBootApplication 的注解和 EnableWebMvc 的注解是存在一定的合并问题的。

而实际的测试结果也发现,确实如果移除了 EnableWebMvc,确实是获取不到 inputStream。

参考

https://www.baeldung.com/spring-request-response-body
https://stackoverflow.com/questions/40247556/spring-boot-automatic-json-to-object-at-controller
https://stackoverflow.com/questions/33796218/content-type-application-x-www-form-urlencodedcharset-utf-8-not-supported-for

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值