POST JSON在415个不受支持的媒体类型Spring3MVC中失败

POST JSON在415个不受支持的媒体类型Spring3MVC中失败

我正在尝试向servlet发送一个POST请求。通过jQuery以这种方式发送请求:

var productCategory = new Object();productCategory.idProductCategory = 1;
productCategory.description = "Descrizione2";newCategory(productCategory);

其中新类别是

function newCategory(productCategory){
  $.postJSON("ajax/newproductcategory", productCategory, function(
      idProductCategory)
  {
    console.debug("Inserted: " + idProductCategory);
  });}

而postJSON是

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback    });};

使用Firebug,我看到正确地发送了JSON:

{"idProductCategory":1,"description":"Descrizione2"}

但是我得到415个不支持的媒体类型。Springmvc控制器有签名

    @RequestMapping(value = "/ajax/newproductcategory", method = RequestMethod.POST)
    public @ResponseBodyInteger newProductCategory(HttpServletRequest request,
        @RequestBody ProductCategory productCategory)

几天前,它起了作用,现在却不起作用了。如果需要的话,我会展示更多的代码。谢谢


收到一只叮咚
浏览 757回答 3
3回答

Helenr

我以前在Spring@ResponseBody中遇到过这种情况,这是因为请求中没有发送Accept头。使用jQuery设置AccepHeader可能会很痛苦,但这对我来说是有效的。来源$.postJSON = function(url, data, callback) {     return jQuery.ajax({     headers: {          'Accept': 'application/json',         'Content-Type': 'application/json'      },     'type': 'POST',     'url': url,     'data': JSON.stringify(data),     'dataType': 'json',     'success': callback    });};@RequestBody使用ContentType标头来确定从请求中从客户端发送的数据的格式。@ResponseBody使用Accept标头来确定将数据发送回响应中的客户端的格式。这就是为什么你需要两个标题。

小唯快跑啊

我也遇到了类似的问题,但发现问题在于,我忽略了为DTO提供一个默认构造函数,该构造函数带有@RequestBody注解。
打开App,查看更多内容
随时随地看视频慕课网APP