具有多个@RequestBody的Spring MVC控制器 [英] Spring MVC controller with multiple @RequestBody

查看:71
本文介绍了具有多个@RequestBody的Spring MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道例如SpringMVC控制器是否可以具有方法签名,例如

I was wondering if for example a SpringMVC controller can have a method signature such as

@RequestMapping(value = "/target", method = RequestMethod.POST)
@ResponseBody
public void acceptObject(@RequestBody MyObjectDto dto,@RequestBody String messageBody) {
    //Authenticate messageBody
    //Process mapped DTO
}

意图是将JSON发布到此控制器,对原始消息主体进行身份验证以确保完整性,如果正确,则将JSON映射到可以移交给处理的DTO.

The intention was that JSON would be posted to this controller, the raw message body would be authenticated for integrity, and if correct, the JSON would be mapped to a DTO that could be handed off for processing.

此刻我结束了

java.io.IOException: Stream closed

推荐答案

Spring使用名为HandlerMethodArgumentResolver的接口来决定将哪些参数传递给处理程序方法.对于用@RequestBody注释的参数,它使用名为

Spring uses an interface called HandlerMethodArgumentResolver to decide which arguments it will pass to your handler methods. For parameters annotated with @RequestBody it uses a class called RequestResponseBodyMethodProcessor. This class basically looks in a set of HttpMessageConverter objects for one that can read the content-type of the request and can convert to the specified type. If it finds one, it passes the body of the HttpServletRequest as an InputStream to the HttpMessageConverter object.

在这种情况下,您可能会发现一些JSON解串器正在工作.很有可能(看到您看到的IOException)消耗了流,然后将其关闭.

In this case, you will probably find some JSON deserializer doing work. It very likely (seeing the IOException you get) consuming the stream and then closing it.

实际上,这种做事方式不可能直接实现.

So really this way to do things isn't directly possible.

一种解决方案是在自己的实现中制作一个将HttpServletRequest包裹起来的Filter,该实现可以缓冲InputStream以使其可重复使用/可重复读取(根据需要多次).但同样,Spring可能会采用从身体反序列化的规则,而这并不是您真正想要的.在这种情况下,您可以创建自己的AnnotationHandlerMethodArgumentResolver,然后在配置中向应用程序注册.然后,您可以控制从请求主体反序列化事物的方式.

One solution is to make a Filter that wraps the HttpServletRequest in your own implementation that buffers the InputStream to make it reusable/re-readable as many times as are required. But again the rules for deserializing from the body might be assumed by Spring and not be what you want exactly. In this case you can create your own Annotation and HandlerMethodArgumentResolver which you then register with the application in your configuration. You can then control exactly how things are deserialized from the request body.

另一种解决方案是将MyObjectDtomessageBody都组合到一个DTO中,如果这对您的数据模型(以及Spring反序列化过程)有意义的话.

Another solution is to combine both MyObjectDto and messageBody into one DTO, if that makes sense to your data model (and to the Spring deserialization process).

这篇关于具有多个@RequestBody的Spring MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆