I am trying to create a Task Reader using Spring MVC. I have a 3 fields in Task: id, Description and dueDate.
Now on "Add Button" click, I am trying to send a Ajax call to the Spring controller. But I am not recieving the request at the server side.
Below is Ajax request code:
function doAjaxPost() {
var id = $('#id').val();
var desc = $('#description').val();
var dueDate = $('#dueDate').val();
var json = { "id" : id, "description" : desc, "dueDate": dueDate};
$.ajax({
type: "POST",
contentType : "application/json",
url: "/addTask",
data : JSON.stringify(json),
dataType : 'json',
success: function(response){
$('#info').html(response);
},
error: function(e){
alert('Error: ' + e);
console.log(e);
}
});
}
And the controller code:
@RequestMapping(value = "/addTask", method = RequestMethod.POST)
public @ResponseBody String addTask(@RequestBody Task task) {
String returnText;
System.out.println(task.getDescription() + " " + task.getDueDate());
System.out.println(task);
// taskList.add(task);
returnText = "User has been added to the list. Total number of task are " + taskList.size();
return returnText;
}
I am getting the below error message in Chrome console.
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method."
Can anybody point me to where am I making the mistake?
Update:
I am able to do it in a alternative way:
@RequestMapping(value = "/addTask" , method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String addTask(@RequestBody String task){
Gson gson = new Gson();
Task t = gson.fromJson(task, Task.class);
taskList.add(t);
ObjectMapper mapper = new ObjectMapper();
String jsontastList = gson.toJson(taskList);
return jsontastList;
}
But I will still like to know the way where I don't need to explicitly convert json to Java object.