简体   繁体   中英

JSON plus spring mvc 3.2 error 415 (Unsupported Media Type)

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.

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

It may be happening because you do not have Jackson on your classpath at runtime.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM