Draaksward
Draaksward

Reputation: 811

Posting a JSON to a Spring Controller

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

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

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";
    }

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.

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

Cant understand what i'm doing wrong.

Upvotes: 0

Views: 120

Answers (1)

Oli
Oli

Reputation: 840

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

Try changing your @RequestMapping annotation to

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

Upvotes: 1

Related Questions