Spring MVC - 空 JSON 与 POST 一起



我对Spring MVC有小问题。基本上,我正在尝试做的是使用AJAX将JSON对象发送到服务器。

简而言之,它看起来像这样,JS代码:

var newUser = { "userId":-1, "userName":name };
var notifRecip = {
  "emailNotification":jQuery( this ).find( "td:nth-child(3) input[type='checkbox']" ).is( ":checked" ),
  "smsNotification":jQuery( this ).find( "td:nth-child(4) input[type='checkbox']" ).is( ":checked" ),
  "webNotification":jQuery( this ).find( "td:nth-child(5) input[type='checkbox']" ).is( ":checked" ),
  "user":newUser
};

如果我是对的,它给了我一个有效的 JSON 对象,其中包含我的表单中的数据是吗?现在我正在做 ajax 帖子:

jQuery.ajax( "/notifications/saveNewUsers/" + notId, {
       dataType:'json',
      contentType:"application/json",
     type:"POST",
    data:( notifRecip )
} )
.success( function ( response )
{
    console.log( response )
} );

到目前为止一切顺利,我的控制器接收具有适当notId值的请求:

@RequestMapping(value = "saveNewUsers/{notificationId}", method = RequestMethod.POST, headers = {"content-type=application/json"})
public
@ResponseBody
boolean saveNewUsers( @RequestBody NotificationRecipient notificationRecipient, @PathVariable Integer notificationId )
{
    System.out.println( notificationId + " " + notificationRecipient );
    return false;
}

但控制台输出是这样的:

18:45:10,947 INFO  [stdout] (ajp--127.0.0.1-8009-1) 0 null

我不知道为什么。我对春季 mvc 很陌生,所以任何帮助将不胜感激。我确实有Jackson依赖性。

NotificationRecipient对象:

public class NotificationRecipient
{
private User user; 
private boolean emailNotification;
private boolean smsNotification;
private boolean webNotification;
//with getters and setters
}

User

public class User
{
private Integer userId;
private String userName;
//with getters and setters
}

经过一段时间的谷歌搜索:

您需要致电data: JSON.stringify( notifRecip ).当我在没有它的情况下进行 POST 时,我的 JSON 对象的参数被解析为 GET 参数( ...webNotificaiton=false&smsNotification=false...)

最新更新