Reputation: 1910
When I try send JSON to Spring MVC Controller I got:
POST http://localhost:8084/springAndHibernate/greet 415 (Unsupported Media Type)
Here is declaration of method which should ,,catch" JSON:
@RequestMapping(headers ={"Accept=application/json"},value="/greet")
public String greetUser(@RequestBody Logins newLogin){
I thought it should map JSON to class Logins.java, which is here:
package newpackage;
public class Logins implements java.io.Serializable {
private int id;
private String login;
private String password;
public Logins() {
}
public Logins(int id) {
this.id = id;
}
public Logins(int id, String login, String password) {
this.id = id;
this.login = login;
this.password = password;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
I send POST with jQuery ajax() method in this way:
function onGreetingButtonClicked(e){
var contextPath='<%=request.getContextPath()%>';
jsonData = {
id: 0,
login: $("#loginInput").val(),
password: $("#passwordInput").val()
};
console.log(JSON.stringify(jsonData));
console.log((contextPath + "/greet").toString());
urlAddress = (contextPath + "/greet")
$.ajax({type: "POST",
url: urlAddress,
data: JSON.stringify(jsonData),
success: onSuccess,
contentType: "application/jsonp; charset=utf-8",
dataType: null,
traditional: true});
e.preventDefault();
}
function onSuccess(data){
alert(data);
}
When I delete
@RequestBody
from method there is no mistakes, but then I get Logins object with null as a fields value.
I would be very happy if anybody want to help me, Thank you in advance.
Upvotes: 0
Views: 408
Reputation: 718678
Based on various other postings, you should be setting the contentType to "application/javascript"
.
I've also seen suggestions to use "application/json"
, but looking at the Wikipedia page, it is clear that JSON-P is actually not valid JSON, so that MIME-type is incorrect, even though some browsers apparently know how to deal with the mistake.
At any rate, "application/jsonp"
is incorrect because it is not a registered MIME-type.
Upvotes: 1