gpt4 book ai didi

java - JSON加spring mvc 3.2报错415(Unsupported Media Type)

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:34 25 4
gpt4 key购买 nike

我做错了什么?我尝试使用 Spring mvc 和 JSON。当我尝试调试我的代码时,我发现 javascript 可以工作但 Controller 不起作用。在浏览器中,我收到错误 415 Unsupported Media Type。

脚本:

$(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();
});

});

Controller :

   @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);
}

最佳答案

这可能是因为您在运行时的类路径中没有 Jackson。

错误消息表明服务器由于某种原因无法处理您的 JSON 请求。 JSON 通过称为消息转换器 的东西转换为 Java 对象。如果你有 <mvc:annotation-driven />在您的 Spring XML 配置中(或者您启用了 Java 配置),JSON 消息转换器会自动注册。如果没有,则必须注册它。

关于java - JSON加spring mvc 3.2报错415(Unsupported Media Type),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com