简体   繁体   English

将JSON发布到Spring Controller

[英]Posting a JSON to a Spring Controller

I'm learning to pass a JSON object through ajax to a Spring Controller. 我正在学习通过ajax将JSON对象传递给Spring Controller。

Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/ 找到了一篇文章,似乎可以解释它是如何完成的: http : //hmkcode.com/spring-mvc-json-json-to-java/

From that point i added a @RequestMapping to the Controller: 从那时起,我向控制器添加了@RequestMapping:

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

Then i'm forming my ajax post: 然后我形成我的ajax帖子:

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. 从“获取用户列表”页面运行。

When i'm trying to run this, i recieve a HTTP 415 error. 当我尝试运行此命令时,我收到HTTP 415错误。 Spring 4, Jackson 2.4 春季4,杰克逊2.4

Cant understand what i'm doing wrong. 不能理解我在做什么错。

HTTP 415 means, that the media type is not supported. HTTP 415表示不支持媒体类型。

Try changing your @RequestMapping annotation to 尝试将@RequestMapping批注更改为

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

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. 您还应考虑在开始实施jQuery客户端之前,使用RESTClient,Postman甚至cURL等客户端测试REST服务,以确保其正常运行。

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

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