JSON发布到Spring Controller [英] JSON post to Spring Controller
问题描述
您好我在Spring中开始使用Web Services,所以我正在尝试在Spring + JSON + Hibernate中开发小型应用程序。我有一些HTTP-POST问题。我创建了一个方法:
Hi I am starting with Web Services in Spring, so I am trying to develop small application in Spring + JSON + Hibernate. I have some problem with HTTP-POST. I created a method:
@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;
}
我的模特测试看起来像:
And my model Test looks like:
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
}
通过POSTMAN我只发送JSON {name:testName}并且我总是收到错误;
By POSTMAN I am sending simply JSON {"name":"testName"} and I always get error;
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
我导入了Jackson库。我的GET方法运行正常。我不知道我做错了什么。我很感激任何建议。
I imported Jackson library. My GET methods works fine. I don't know what I'm doing wrong. I am grateful for any suggestions.
推荐答案
使用
JSON.stringify({name:testName})
或手动。 @RequestBody期待json字符串而不是json对象。
or manually. @RequestBody expecting json string instead of json object.
注意:stringify函数有一些IE版本有问题,firefox会有效吗
Note:stringify function having issue with some IE version, firefox it will work
验证您的POST请求的ajax请求的语法。 ajax请求中需要 processData:false 属性
verify the syntax of your ajax request for POST request. processData:false property is required in ajax request
$.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
@RequestBody
-Covert Json object to java
@ResponseBody
- 将Java对象转换为json
@ResponseBody
- convert Java object to json
这篇关于JSON发布到Spring Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!