我正在使用 Backbone.js 和 Spring mvc 开发 Google App Engine 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 Controller 无法读取请求参数。或者,我尝试使用 HttpServletRequest 和 request.getParameter("title") 而不使用自动绑定(bind),但返回的值仍然为 null。 请求中发送的数据:
{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来读取请求参数。
关于google-app-engine - Spring MVC 3.2 Backbone.js 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31123909/