JSON发布到Spring Controller
问题内容:
嗨,我从Spring的Web Services开始,所以我试图在Spring + JSON + Hibernate中开发小型应用程序。我对HTTP-
POST有问题。我创建了一个方法:
@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
String name = test.name;
return name;
}
我的模型测试看起来像:
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
}
通过POSTMAN,我仅发送JSON {“ name”:“ testName”},但我总是收到错误;
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
我导入了杰克逊图书馆。我的GET方法工作正常。我不知道我在做什么错。我很感谢任何建议。
问题答案:
使用将您的JSON对象转换为JSON字符串
JSON.stringify({“ name”:“ testName”})
或手动。 @RequestBody需要json字符串 而不是json对象。
注意:stringify函数在某些IE版本中存在问题,firefox可以使用
验证POST请求的ajax请求的语法。Ajax请求中需要 processData:false 属性
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
// Success Action
}
});
控制者
@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {
//do business logic
return test;
}
@RequestBody
-将Json对象转换为Java
@ResponseBody
-将Java对象转换为json