[英]In Spring MVC using jquery ajax with json, getting error : “unsupported media type”
I am creating Spring MVC application, in JSP I need to send object to controller and then return the object to jsp. 我正在创建Spring MVC应用程序,在JSP中,我需要将对象发送到控制器,然后将对象返回到jsp。 But I am getting "Unsupported media type" error.
但是我收到“不支持的媒体类型”错误。 Could someone help me ?
有人可以帮我吗? below is my code:
下面是我的代码:
** In Controller : **在控制器中:
@RequestMapping(value = "/addPerson", method = RequestMethod.POST,
headers = {"Content-type=application/json" })
@ResponseBody
public Person addPerson(@RequestBody Person person) {
System.out.println(person.getName());
return person;
}
**In JSP : **在JSP中:
$.ajax({
type: "POST",
url: "addPerson.view",
data: JSON.stringify({ name: "Adam", age: 30, city: "Paris" }),
contentType: 'application/json',
success: function(data) {
alert(data.name + " has been added");
},
error : function(xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("error : " + errorMessage);
}
});
Try this: 尝试这个:
@RequestMapping(value = "/addPerson", method = RequestMethod.POST, consumes= {"application/json"}) @RequestMapping(值=“ / addPerson”,方法= RequestMethod.POST,消耗= {“ application / json”})
For Spring to deserialize JSON from the request body and provide the generated object to a @RequestBody
annotated parameter, you need to have Jackson (1 or 2) on the classpath. 为了让Spring从请求主体反序列化JSON并将生成的对象提供给
@RequestBody
注释参数,您需要在类路径上具有Jackson(1或2)。 If Spring detects Jackson, it will register a MappingJackson2HttpMessageConverter
which will do the conversion. 如果Spring检测到Jackson,它将注册一个
MappingJackson2HttpMessageConverter
来进行转换。 This HttpMessageConverter
can handle application/json
content. 此
HttpMessageConverter
可以处理application/json
内容。 No other default HttpMessageConverter
can, which is why you get an Unsupported media type error. 没有其他默认的
HttpMessageConverter
可以,这就是为什么您收到不支持的媒体类型错误的原因。
contentType:“应用程序/ json; charset = UTF-8”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.