【问题标题】:AJAX JSON post to Spring controller returns HTTP 415AJAX JSON 发布到 Spring 控制器返回 HTTP 415
【发布时间】:2012-12-07 22:38:31
【问题描述】:

我已阅读 StackOverflow 上有关此问题的大部分帖子,并尝试了许多修复程序,但最终没有解决我的问题。 Spring 抛出 HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

我有一个这样定义的控制器:

 @RequestMapping(method = RequestMethod.POST, value = "/update")
 public @ResponseBody JSONDomainResponse update(@RequestBody Model inModel)

模型如下所示:

public class Model implements Serializable {

private static final long serialVersionUID = 2738522159847487651L;
private String id;
private BigDecimal offset;

@JsonCreator
public Model(@JsonProperty("id") String id, @JsonProperty("offset") BigDecimal offset) {
  this.id = id;
  this.offset = offset;
}

public String getID() {
  return id;
}

public BigDecimal getOffset() {
  return offset;
}

public void setID(String id) {
  this.id = id;
}

public void setOffset(BigDecimal offset) {
  this.offset = offset;
}
}

我尝试使用的 AJAX 调用如下所示:

$.ajax({
  type : 'POST',
  url : '/update',
  contentType : "application/json",
  data : JSON.stringify({"id":"test", "offset":300})
 });

我的 context.xml 文件中有 <mvc:annotation-driven/> 配置,并且我已验证 MappingJacksonHttpMessageConverter 的 canRead() 方法为我的模型和 JSON 媒体类型返回 true。

我的类路径中还指定了 Jackson 核心和映射器 jar。

我注意到从控制器签名中删除模型参数使得我实际上通过我的帖子到达控制器,这让我相信我的模型存在一些问题。但是,由于记录的信息很少,我无法确定问题所在。

提前致谢。

【问题讨论】:

    标签: java ajax json spring spring-mvc


    【解决方案1】:

    我终于找到了解决问题的方法,这很简单,但完全不明显。

    原来我试图反序列化的模型对象位于一个命名不正确的包中,当 Spring 无法找到该模型时,它只会吞下生成的异常并返回 false。我通过在 Spring-MVC 领域的深入调试发现了这一点,尤其是 StdDeserializerProvider 类。

    对于其他收到此错误的人,我强烈建议编写一些代码来验证此类中发生的情况,例如:

    @Test
    public void testThatCanConvertUpdateModel() {
      MappingJacksonHttpMessageConverter conv = new MappingJacksonHttpMessageConverter();
      assertTrue(conv.canRead(YourModel.class, MediaType.APPLICATION_JSON));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      相关资源
      最近更新 更多