Java 通过 POST 和 SPRING-MVC 发送多个对象的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19654120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:10:21  来源:igfitidea点击:

Problems sending multiple objects through POST and SPRING-MVC

javajsonspringspring-mvc

提问by mannuk

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

我正在开发必须接收多个信息的 REST 服务。在这种情况下,两个对象和一个属性。

This is the javascript where I'm testing the POST request

这是我测试 POST 请求的 javascript

    var user = {
        username: "admin",
        password: "admin"
    };
    var userToSubscribe = {
        username: "newuser",
        password: "newpassword",
        email: "[email protected]"
    };

    var openid = "myopenid";

    $.ajax({
        url: '/myportal/rest/subscribeUser.json',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        mimeType: 'application/json',
        data: JSON.stringify({ user: user, userToSubscribe: userToSubscribe, openid: openid})    
    });

The POST request:

POST 请求:

    JSON


    openid
        "myopenid"

    user
        Object { username="admin", password="admin"}

    userToSubscribe
        Object { username="newuser", password="newpassword", email="[email protected]"}
    Source
    {"user":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"[email protected]"},"openid":"myopenid"}

And the controller which handles the POST:

以及处理 POST 的控制器:

    @RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public @ResponseBody Message subscribeUser(@RequestBody("user") User user, @RequestBody("userToSubscribe") User userToSubscribe, @RequestParam String openid){
    ...
}

And the error is

错误是

POST subscribeUser.json 400 Incorrect request localhost:8080 990 B [::1]:8080

POST subscribeUser.json 400 不正确的请求 localhost:8080 990 B [::1]:8080

What am i doing wrong?

我究竟做错了什么?

Thank you

谢谢

采纳答案by Chinmay

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:

请求正文将包含整个 JSON 内容。所以当你想映射 JSON 时,你只使用一个 RequestBody 注释参数。你将不得不做这样的事情:

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.

然后使用映射器的 convertValue 方法从字符串中获取不同的对象。

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

Similarly for the other objects

其他对象类似

回答by CodeChimp

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.

您不能@ModelAttribute在接受 JSON 的 RESTful 方法中使用s。我相信正确的方法是使用@RequestBody,就像这里所做的那样。您很可能需要将对象包装在某个包装器类中,但我可能错了,因为我以前从未亲自尝试过在一个请求中传递多个 JSON 对象。

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.

也就是说,我认为如果您重新考虑您的 REST api,删除 JSON 参数并将它们作为 URI 路径的一部分传入,如果可能的话,这将是一个好主意。我建议通读这篇博文

回答by Harish Bagora

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

您可以创建一个包含所有对象的 java bean(POJO),例如..

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..

并将这个 bean 传递给 Web 服务。所以网络服务看起来像..

@RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public @ResponseBody Message subscribeUser(@RequestBody JavaBean javaBean) {
    ...
}