java AJAX JSON post到Spring控制器返回HTTP 415
我已经阅读了有关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})
});
在我的上下文中有<mvc:annotation-driven/>
配置。xml文件,我已经验证了MappingJacksonHttpMessageConverter
的canRead()方法对于我的模型和JSON媒体类型返回true
我的类路径中也指定了Jackson core和mapper JAR
我注意到,从控制器签名中删除模型参数会使我的帖子实际到达控制器,这使我相信我的模型存在一些问题。但是,由于记录的信息很少,所以我无法真正说出问题出在哪里
提前谢谢
# 1 楼答案
我终于找到了这个问题的解决办法,虽然很琐碎,但完全不明显
事实证明,我试图反序列化的模型对象位于一个命名不正确的包中,当Spring无法定位该模型时,它只是吞下生成的异常并返回false。我通过在SpringMVC领域的深层调试发现了这一点,特别是StdDeserializerProvider类
对于收到此错误的其他人,我强烈建议编写一些代码来验证此类中发生的情况,例如: