简体   繁体   English

Spring MVC @RequestBody和部分对象/ json绑定

[英]Spring MVC @RequestBody and partial object/json binding

I have a large object which can be updated in a few steps. 我有一个大的对象,可以通过几个步骤进行更新。 I'am facing a partial binding problem. 我正面临部分约束问题。 My service consumes json and I can not use @InitBinder along with @RequestBody. 我的服务使用json,我不能使用@InitBinder和@RequestBody。 Cutting this object to a few small ones is not good a solution, because there is a lot of cross-field validations between steps. 将这个对象切割成几个小对象并不是一个好的解决方案,因为步骤之间有很多跨场验证。

Do you have any ideas how to solve this? 你有任何想法如何解决这个问题? I'am looking for a clean solution like: registering a specific object mapper for given @RequestMapping or something like that. 我正在寻找一个干净的解决方案,例如:为给定的@RequestMapping注册特定的对象映射器或类似的东西。 Thanks for help. 感谢帮助。

You should be able to use a PATCH HTTP method 您应该能够使用PATCH HTTP方法

Its the preferred method that you would use when you need partial updates, like in your case when you want to update just a few fields of a resource 它是您在需要部分更新时使用的首选方法,例如在您只想更新资源的几个字段时

Spring MVC added a support for it in the version 3.2, so you can do something like Spring MVC在版本3.2中添加了对它的支持,所以你可以做类似的事情

@RequestMapping(value="/patch", method=RequestMethod.PATCH, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String patch(@RequestBody Foo foo)    {
    return foo.toString();
}

and when sending the request, add only the properties you want to update to your PATCH request, the properties that are null or omited won't be updated 并且在发送请求时,仅将要更新的属性添加到PATCH请求中,将不会更新null或省略的属性

In the lack of better Spring MVC PATCH reference, I'm linking this SO thread as an interesting read Spring MVC PATCH method: partial updates 在缺少更好的Spring MVC PATCH参考时,我将这个SO线程作为一个有趣的读取Spring MVC PATCH方法进行链接:部分更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM