为了账号安全,请及时绑定邮箱和手机立即绑定

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

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)几天前,它起了作用,现在却不起作用了。如果需要的话,我会展示更多的代码。谢谢
查看完整描述

3 回答

?
Helenr

TA贡献1780条经验 获得超3个赞

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


查看完整回答
反对 回复 2019-07-05
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

我也遇到了类似的问题,但发现问题在于,我忽略了为DTO提供一个默认构造函数,该构造函数带有@RequestBody注解。


查看完整回答
反对 回复 2019-07-05
  • 3 回答
  • 0 关注
  • 751 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信