我在Spring MVC上有一个简单的Java应用程序,并向Spring控制器发送ajax请求。当我设置头“接受”, “应用/ JSON”和“内容类型”, “应用/ JSON的;字符集= UTF-8”在AJAX调用我得到错误时400在dubugger,我删除它我得到错误415。Spring MVC + Ajax错误400
如果我改变控制器方法签名公共字符串logoutPage(@RequestBody字符串obyavleniye)我得到JSON字符串。在控制器中解析请求会有什么问题?
JS方法:
$("#advertForm").submit(function(e) {
e.preventDefault();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var obyavleniye = {
title: "Title",
price: "80",
description: "desc",
date: "2016-11-07 18:30:21",
authorid: "2",
category: "A",
state: "new",
img1: "http",
img2: "http",
img3: "http",
img4: "http",
};
var post_data = JSON.stringify(obyavleniye);
console.log(post_data);
$.ajax({
url : "/upload",
type: "POST",
dataType: 'json',
data: post_data,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader(header, token);
},
complete: function() {
console.log("Sent");
},
success: function (response) {
console.log("success");
console.log("response" + response);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
控制器方法:
@ResponseBody
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String logoutPage (@RequestBody Advert obyavleniye) {
// public String logoutPage (@RequestBody String obyavleniye) {
System.out.println("Enter: " + obyavleniye);
this.advertService.addAdvert(obyavleniye);
// return "{\"msg\":\"success\"}";
return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
}
请指定广告类的属性。 –