Error to Pass JSON data from JSP to controller in ResponseBody.
07:13:53.919 DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from
I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json
) and it worked, as you can see on the image below
Try this:
@RequestBody(required = false) String str
Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.
You shouldn't send a request body with an HTTP GET request. You should modify addDepartment()
so that it only supports POST, and POST your JSON to that endpoint. If you want to GET information about a department, you should create a separate controller method that does that (and does not require a request body).
Also, double-check your endpoint definitions since you have misspelled "reimbursement" in the $.ajax
call.
If it's working from Postman, try new Spring version, becouse the 'org.springframework.boot' 2.2.2.RELEASE version can throw "Required request body content is missing" exception.
Try 2.2.6.RELEASE version.
I made some minor modification to you code and tested it with a spring project that I have and it works, The logic will only work with POST if I use GET it throws an error with invalid request. Also in your ajax call I commented out commit(true), the browser debugger flagged and error that it is not defined. Just modify the url to fit your Spring project architecture.
$.ajax({
url: "/addDepartment",
method: 'POST',
dataType: 'json',
data: "{\"message\":\"abc\",\"success\":true}",
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.success + " " + data.message);
//commit(true);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
@RequestMapping(value="/addDepartment", method=RequestMethod.POST)
public AjaxResponse addDepartment(@RequestBody final AjaxResponse departmentDTO)
{
System.out.println("addDepartment: >>>>>>> "+departmentDTO);
AjaxResponse response=new AjaxResponse();
response.setSuccess(departmentDTO.isSuccess());
response.setMessage(departmentDTO.getMessage());
return response;
}