将JSON发布到Spring Controller

问题描述:

我正在学习通过ajax将JSON对象传递给Spring Controller.

I'm learning to pass a JSON object through ajax to a Spring Controller.

找到了一篇文章,似乎可以解释它是如何完成的: http://hmkcode.com/spring-mvc-json-json-to-java/

Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/

从那时起,我向控制器添加了@RequestMapping:

From that point i added a @RequestMapping to the Controller:

@RequestMapping(value = "/get-user-list", method = RequestMethod.POST)
    public @ResponseBody String testPost(@RequestBody ResourceNumberJson resourceNumberDtoJson) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>> I AM CALLED");
        return "111";
    }

然后我正在形成我的ajax帖子:

Then i'm forming my ajax post:

var json = {
    "login" : "login",
    "resource_number" : "111",
    "identifier" : "1111",
    "registrator_number" : "11111111111111"
};
console.log(JSON.stringify(json));
$.ajax({
    type : "POST",
    url : "/get-user-list",
    dataType : "text",
    data : JSON.stringify(json),
    contentType : 'application/json; charset=utf-8',
    mimeType: 'application/json',
    success: function(data) { 
            alert(data.id + " " + data.name);
        },
    error:function(data,status,er) { 
            alert("error: "+data+" status: "+status+" er:"+er);
    }

});

从获取用户列表"页面运行.

which is runned from "get-user-list" page.

当我尝试运行此命令时,我收到HTTP 415错误.春季4,杰克逊2.4

When i'm trying to run this, i recieve a HTTP 415 error. Spring 4, Jackson 2.4

不能理解我在做什么.

HTTP 415 表示不支持媒体类型.

HTTP 415 means, that the media type is not supported.

尝试将您的@RequestMapping批注更改为

Try changing your @RequestMapping annotation to

@RequestMapping(value = "/get-user-list", 
                method = RequestMethod.POST, 
                consumes="application/json")

您还应该考虑在开始实施jQuery客户端之前,使用RESTClient,Postman甚至cURL之类的客户端测试REST服务,以确保其正常运行.

You should also consider testing your REST-service with a client like RESTClient, Postman or even cURL to make sure it is working correctly before you start implementing the jQuery client.