I am trying to send a POST request to a servlet. Request is sent via jQuery in this way:
var productCategory = new Object();
productCategory.idProductCategory = 1;
productCategory.description = "Descrizione2";
newCategory(productCategory);
where newCategory is
function newCategory(productCategory)
{
$.postJSON("ajax/newproductcategory", productCategory, function(
idProductCategory)
{
console.debug("Inserted: " + idProductCategory);
});
}
and postJSON is
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};
With firebug I see that JSON is sent correctly:
{"idProductCategory":1,"description":"Descrizione2"}
But I get 415 Unsupported media type. Spring mvc controller has signature
@RequestMapping(value = "/ajax/newproductcategory", method = RequestMethod.POST)
public @ResponseBody
Integer newProductCategory(HttpServletRequest request,
@RequestBody ProductCategory productCategory)
Some days ago it worked, now it is not. I'll show more code if needed. Thanks
1.a. Add following in applicationContext-mvc.xml
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc
I managed out how to make it works. Tell me in case I am wrong. I used only one way to serialize/deserialize: I removed all annotations regarding this (
@JSONSerialize
and@JSONDeserialize
) and registered Serializers and Deserializers inCustomObjectMapper
class. I didn't find an article explaining this behaviour but I resolved in this way. Hope it's useful.I had a similar problem but found the issue was that I had neglected to provide a default constructor for the DTO that was annotated with @RequestBody.
A small side note - stumbled upon this same error while developing a web application. The mistake we found, by toying with the service with Firefox Poster, was that both fields and values in the Json should be surrounded by double quotes. For instance..
In our case we filled the json via javascript, which can be a little confusing when it comes with dealing with single/double quotes, from what I've heard.
What's been said before in this and other posts, like including the 'Accept' and 'Content-Type' headers, applies too.
Hope t'helps.
Spring boot + spring mvn
with issue @PostMapping("/addDonation") public String addDonation(@RequestBody DonatorDTO donatorDTO) {
with solution @RequestMapping(value = "/addDonation", method = RequestMethod.POST) @ResponseBody public GenericResponse addDonation(final DonatorDTO donatorDTO, final HttpServletRequest request){
I had the same problem. I had to follow these steps to resolve the issue:
1. Make sure you have the following dependencies:
2. Create the following filter:
3. Apply the above filter for the requests in web.xml
I hope this is useful to somebody.