SpringMVC 3.2Backbone.jsPost

Spring MVC 3.2 Backbone.js Post

我正在使用 Backbone.js 和 Spring mvc 开发 Google App 引擎 Web 应用程序。我有以下 backbone.js 代码:

       var PostModel = Backbone.Model.extend({
            defaults: {
               "title": "",
               "postTxt": ""
            }
        });

        var PostCollection = Backbone.Collection.extend({
              url: '/createUserPost',
              model: PostModel
        });

        var postcollection = new PostCollection();


      function createPost() {


           var postview = new PostView();
           postcollection.create({ title: $('#title').val(), postTxt:   $('#postTxt').val() });

           title: $('#title').val('');
           post: $('#postTxt').val('');

       }

Spring 后端mvc 3.2代码:

 @RequestMapping(value = "/createUserPost", method=RequestMethod.POST)
 public @ResponseBody UserPosts createUserPost(   @ModelAttribute(value="post")  UserPosts post, 

@CookieValue(value = "sessionId", defaultValue = "null") String sessionId) {

    //my custom method to get user name by querying the datastore
    String author = getAuthorFromSessionId(sessionId);              

    PersistenceManager pm = PMF.get().getPersistenceManager();

    try {


        post.setAuthor(author);
        pm.makePersistent(post);

    }
    finally {

        pm.close();

    }



    return post;
}

单击 post 按钮时,文本会正确添加到 HTML 并向服务器发出 POST 请求,状态代码为 200 OK。 Spring 控制器无法读取请求参数。或者,我尝试在没有自动绑定的情况下使用 HttpServletRequest 和 request.getParameter("title"),但返回的值仍然为空。 请求中发送的数据:

             {title: "kdkldklfd", postTxt: "kkfdlksffkl"}

收到回复:

             {"title":null,"author":"admin","postTxt":null}
@RequestMapping(value = "/createUserPost", method=RequestMethod.POST, 
consumes = "application/json", produces = "application/json")
public @ResponseBody UserPosts createUserPost(@RequestBody  UserPosts post) {

应该使用@RequestBody 注释代替@ModelAttribute 来读取请求参数。