My Spring controller and client side Javascript code are as follows and for some reason the Javascript object is unable to reach the Spring controller in the Object form. My Controller code is as follows:
@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {
if(employeeRating.getId()==0)
{
employeeRatingService.addRating(employeeRating);
}
else
{
employeeRatingService.updateRating(employeeRating);
}
return employeeRating;
}
My Javascript code below:
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: {
'id':5,
'name': 'Name',
'rating': '1'
},
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});
The EmployeeRating object in Java has id, name and rating fields so there's no mismatch.
Updating the model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* This is our model class and it corresponds to Country table in database
*/
@Entity
@Table(name="EMPLOYEERATING")
public class EmployeeRating {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
@Column(name="name")
String name;
@Column(name="rating")
long rating;
public EmployeeRating() {
super();
}
public EmployeeRating(int i, String name,long rating) {
super();
this.id = i;
this.name = name;
this.rating=rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getRating() {
return rating;
}
public void setRating(long rating) {
this.rating = rating;
}
}
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
'id':5,
'name': 'Name',
'rating': '1'
}),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});