【问题标题】:spring mvc - null json with postspring mvc - 带有帖子的空 json
【发布时间】:2012-06-25 16:59:31
【问题描述】:

我对 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 post:

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

我不知道为什么。我对spring 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
}

【问题讨论】:

  • 你可以发布 JSON,然后发送到控制器吗?(在萤火虫中查看并发布)

标签: java jquery ajax spring-mvc


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-01-03
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2018-10-29
    • 2017-07-16
    • 2017-01-10
    • 2019-03-30
    • 2017-07-09
    相关资源
    最近更新 更多