Problems sending multiple objects through POST and SPRING-MVC

前端 未结 3 1050
一整个雨季
一整个雨季 2021-01-05 04:43

I\'m developing REST services which have to receive multiple info. In this case, two objects and an attribute.

This is the javascript where I\'m testing the POST req

相关标签:
3条回答
  • 2021-01-05 05:04

    You cannot use @ModelAttributes in a RESTful method that accepts JSON. I believe the proper method is to use @RequestBody, as done here. You will most likely need to wrap the objects in some wrapper class, but I could be wrong there as I have never personally tried to pass multiple JSON objects in one request before.

    That said, I think it would be a good idea if you rethought your REST api, removing the JSON arguments and instead passing them in as part of the URI path, if possible. I would suggest reading through this blog post.

    0 讨论(0)
  • 2021-01-05 05:11

    The request body will contain the entire JSON content. So when you want to map the JSON, you use only one RequestBody annotated-parameter. You will have to do something like this:

    public @ResponseBody Message subscribeUser(@RequestBody String str)
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(str);
    

    And then use the convertValue method of the mapper to get your different objects from the string.

    JsonNode node = mapper.readTree(str);
    User theUser = mapper.convertValue(node.get("user"), User.class);
    

    Similarly for the other objects

    0 讨论(0)
  • 2021-01-05 05:13

    You can create a java bean(POJO) containing all the objects like..

    class JavaBean{
        private User user;
        private UserTOSubscribe  userToSubscribe;
        private Long openId;
    
        // getter and setter
    }
    

    and pass this bean in to the Web service. so web service looks like..

    @RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
    public @ResponseBody Message subscribeUser(@RequestBody JavaBean javaBean) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题