0
我想將JSON對象發佈到使用JQ的Ajax在Java中創建的REST,但是,我收到「不受支持的媒體類型」錯誤。使用JQ發佈JSON對象到REST
這裏是控制器方法:
@ResponseBody
@RequestMapping(value = "postrest", method = RequestMethod.POST, consumes = "application/json")
public String postRest(@RequestBody Person person) throws InterruptedException{
Thread.sleep(5000);
return "Congrats on successfully posting, " + person.getName() + "!";
}
這裏是POJO:
package domain;
public class Person {
private String name;
public Person(){}
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
這裏是JavaScript的:
var person = {};
person.name = "milan";
$.ajax({
url: "http://localhost:8084/app/postrest",
type: "post",
data: person,
contentType: "application/json; charset=utf-8",
dataType: "text",
context: document.body
}).done(function(response) {
console.log(response);
});
編輯:原來,這甚至不工作如果我使用老式的Ajax,因爲服務器應用程序沒有Jackson。現在我可以使用老式的方式工作,但我仍然無法修復JQ變體。這裏是老式的阿賈克斯代碼:
var person = {};
person.name = "milan";
var xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8084/springsecurityalternative/postrest", false); //notice that the URL is different here, this is because I'm running using a different app that has Jackson
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(person));
xhr.responseText;