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

新手上路,请多包涵

我正在尝试向 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
    });
};

使用萤火虫,我看到 JSON 已正确发送:

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

但是我得到 415 Unsupported media type。 Spring mvc 控制器有签名

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

前几天还管用,现在不行了。如果需要,我会显示更多代码。

原文由 gc5 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 531
2 个回答

我设法让它发挥作用。告诉我以防万一我错了。我只使用一种方法来序列化/反序列化:我删除了所有关于此的注释( @JSONSerialize@JSONDeserialize )并在 CustomObjectMapper 中注册了序列化器和反序列化器我没有找到解释这种行为的文章,但我以这种方式解决了。希望它有用。

原文由 gc5 发布,翻译遵循 CC BY-SA 3.0 许可协议

我以前在 Spring @ResponseBody 中遇到过这种情况,这是因为没有随请求发送的接受标头。使用 jQuery 设置接受标头可能会很痛苦,但这对我 有用

$.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 标头来确定在响应中将数据发送回客户端的格式。这就是为什么你需要两个标题。

原文由 theon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题