Java JSON 加 spring mvc 3.2 错误 415(不支持的媒体类型)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21344352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON plus spring mvc 3.2 error 415 (Unsupported Media Type)
提问by user3233853
What did I do wrong? I try to use Spring mvc and JSON. When I try to debug my code I am looking that javascript works but doesn't works controller. In browser I get error 415 Unsupported Media Type.
我做错了什么?我尝试使用 Spring mvc 和 JSON。当我尝试调试我的代码时,我正在寻找 javascript 工作但不工作控制器。在浏览器中,我收到错误 415 Unsupported Media Type。
Script:
脚本:
$(document).ready(function() {
$('#newSmartphoneForm').submit(function(event) {
var producer = $('#producer').val();
var model = $('#model').val();
var price = $('#price').val();
var json = { "producer" : producer, "model" : model, "price": price};
$.ajax({
url: $("#newSmartphoneForm").attr( "action"),
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(smartphone) {
var respContent = "";
respContent += "<span class='success'>Smartphone was created: [";
respContent += smartphone.producer + " : ";
respContent += smartphone.model + " : " ;
respContent += smartphone.price + "]</span>";
$("#sPhoneFromResponse").html(respContent);
}
});
event.preventDefault();
});
});
Controllers:
控制器:
@RequestMapping(value="/create", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
return smartphoneService.create(smartphone);
}
采纳答案by Alexey
It may be happening because you do not have Hymanson on your classpath at runtime.
这可能是因为在运行时您的类路径上没有 Hymanson。
The error message says that the server cannot handle your JSON request for some reason. JSON is converted to a Java object with a thing that is called message converter. If you have <mvc:annotation-driven />
in your Spring XML config (or you have Java Config enabled), the JSON message converter is registered automatically. If you don't, you have to register it.
错误消息表示服务器由于某种原因无法处理您的 JSON 请求。JSON 被转换为 Java 对象,该对象称为消息转换器。如果您<mvc:annotation-driven />
的 Spring XML 配置中有(或启用了 Java Config),则 JSON 消息转换器会自动注册。如果没有,则必须注册。