Sending JSON Data to Server Error

2019-05-21 06:30发布

问题:

I want to sent a JSON data to my controller's POST handler. I do that at my client side:

var userName = $('#userName').val();
var password = $('#password').val();
var mail = $('#mail').val();
var admin =$("#admin").is(':checked');
var user = {userName: userName, password: password, mail: mail, admin:admin};

$.ajax({
   async : false,
   type:'POST',
   url: '/uxiy/webapp/uxmer',
   data: user,
   dataType: 'json',
   success: function(data) {
       ...
   },
   error: function(data) {
       ...
   }
});

My Spring controller as follows:

@RequestMapping(method = RequestMethod.POST)
public void createUser(HttpServletResponse response, @RequestBody User user) {
    user.setName("POST worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    response.setStatus(HttpServletResponse.SC_OK);
}

However when I send my data I get that error at Firebug:

"NetworkError: 415 Unsupported Media Type"

What is wrong?

PS: An example of Firebug POST details:

Parameters  application/x-www-form-urlencoded
admin   true
mail    user@user.com
password    r
userName    userx
Source
userName=userx&password=r&mail=user%40user.com&admin=true

PS2: After I added

contentType: 'application/json',

it started to give

"NetworkError: 400 Bad Request" 

What can be the problem, making serialization, etc?

PS3: Here: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ it says:

If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned.

I have 400 Bad Request Error. Maybe the problem is related to that?

回答1:

Problem was about the JSON array. It was not a valid JSON string that was sent from client to server.


Edit

To clarify this, I stumbled upon this post. It is required to do a proper JSON.stringify(data) in the Ajax request. It's strange but it's not done by the .ajax function when setting the corresponding dataType.

$.ajax({
    async : false,
    type:'POST',
    url: '/uxiy/webapp/uxmer',
    data: JSON.stringify(user),
    dataType: 'json',
    success: function(data) {
        ...
    },
    error: function(data) {
        ...
    }
});


回答2:

Set the content type to application/json or Jackson won't kick in.

$.ajax({
   async : false,
   type:'POST',
   contentType: 'application/json',
   url: '/uxiy/webapp/uxmer',
   data: user,
   dataType: 'json',
   success: function(data) {
       ...
   },
   error: function(data) {
       ...
   }
});


回答3:

You need to set the media type that is accepted by your controller.

Documentation:

http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html

Take a look at ContentNegotiatingViewResolver

The Accept: header is mostly what you need to be concerned about.