springMVC中,V代表View,controller需要将model(M)生成的数据在合适的view(V)上面显示出来,如果我们只是将想model中的数据以stream的形式显示出来如何呢?
1.@RequestBody
它能将post中的数据序列化到函数的参数中
2. @ResponseBody
It can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
这两个注解必须要通过HttpMessageConverter 完成responsebody到java bean之间的相互转化,目前spring默认提供的几种HttpMessageConverter包含:
ByteArrayHttpMessageConverter converts byte arrays.
StringHttpMessageConverter converts strings.
FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
如果body的内容是其它自定义的类型,需要定义自定义的HtppMessageConverter来完成转化,否则会失败。
3.ResponseEntity
这个类不仅可以存储responsebody,还能够存储response header以及http status,被它存储的对象也是直接在浏览器中输出,不会被拦截进而转发到view上去,这个类含有多种构造函数,通过设置response header能够生成各种各样类型的数据,如json、csv类型的。
参考资料:
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
https://www.captaindebug.com/2011/07/using-springs-responsebody-annotation.html#.U0zx6PmSzv0
https://www.captaindebug.com/2011/07/using-spring-responseentity-class.html#.U0zuiPmSzv0
https://www.beabetterdeveloper.com/2013/07/spring-mvc-requestbody-and-responsebody.html