Ajax and Spring MVC can't get list to spring method
When I try to send a list with ajax to a method in spring controller I get this error:
Content type 'application/x-www-form-urlencoded' not supported
my AJAX code:
$('#btn-save').click(
ajaxSend();
);
function ajaxSend() {
$.ajax({
url: "/kepres2Web/mvc/spatiu/update",
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=UTF-8",
data: JSON.stringify(rects),
success: function (data) {},
error: function (data, status, er) {},
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
});
}
my method:
@RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"application/json", "application/xml"}, consumes = {"application/x-www-form-urlencoded"})
public String update(@ModelAttribute("record") Spatiu spatiu,@RequestBody List<Desk> deskList) {
System.out.println(deskList.get(0).getFill());
dao.update(spatiu);
//return null;
return "redirect:view?ls&id=" + spatiu.getId();
}
and my button:
<button id="btn-save" type="submit" form="frmDetails" formaction="update">
<img src="${pageContext.request.contextPath}/img/actions/save.png">
<br>Salvare
</button>
EDIT
Found out that Spring doesn't understand application/x-www-form-urlencoded as RequestBody so I removed it and added @ResponseBody on method. Now it returns and empty list.
Couple of things to fix in your code.
You have defined headers 2 times. Headers defined by headers takes precedence. You need to remove that to be able to send json data your service.
On @RequestMapping you need to define consumes in order to accept the data as json. Check if you have by default json as accepted data otherwise configure explicitly using consumes.
@RequestMapping(value = "URL", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
链接地址: http://www.djcxy.com/p/48466.html