JSON plus spring mvc 3.2 error 415(不支持的媒体类型)

use*_*853 4 javascript java ajax spring-mvc

我做错了什么?我尝试使用Spring mvc和JSON.当我尝试调试我的代码时,我看起来javascript工作,但不适用于控制器.在浏览器中,我收到错误415不支持的媒体类型.

脚本:

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

});  
Run Code Online (Sandbox Code Playgroud)

控制器:

   @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);
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*xey 5

它可能正在发生,因为你在运行时没有杰克逊在你的类路径上.

错误消息表明服务器由于某种原因无法处理您的JSON请求.JSON被转换为Java对象,其中包含一个称为消息转换器的东西.如果您已<mvc:annotation-driven />在Spring XML配置中(或启用了Java Config),则会自动注册JSON消息转换器.如果不这样做,则必须注册.