小编典典

POST JSON失败,显示415不支持的媒体类型,Spring 3 mvc

spring

我正在尝试向Servlet发送POST请求。通过jQuery通过以下方式发送请求:

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

newCategory在哪里

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不支持的媒体类型。Spring MVC控制器具有签名

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

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


阅读 500

收藏
2020-04-11

共1个答案

小编典典

我以前在Spring @ResponseBody中发生过这种情况,这是因为没有随请求一起发送的accept标头。使用jQuery设置Accept标头可能很麻烦,但这对我有用

$.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使用Content-Type标头确定从客户端在请求中发送的数据的格式。@ResponseBody使用accept标头确定响应中将数据发送回客户端的格式。这就是为什么你需要两个标题。

2020-04-11