2014-01-24 2 views
4

내가 뭘 잘못 했습니까? 나는 봄 mvc와 JSON을 사용하려고한다. 내 코드를 디버깅하려고 할 때 자바 스크립트가 작동하지만 컨트롤러가 작동하지 않습니다. 브라우저에서 415 Unsupported Media Type 오류가 발생합니다.JSON plus spring mvc 3.2 오류 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(); 
    }); 

}); 

컨트롤러 :

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

사용중인 Spring MVC 버전은 무엇입니까? 네트워크 콘솔을여십시오. 'Content-Type' 헤더를 보셨습니까? 우리에게'스마트 폰'수업을 보여주세요. –

답변

5

런타임에 클래스 경로에 잭슨이 없기 때문에 그것은 일이 될 수 있습니다.

오류 메시지는 서버가 어떤 이유로 JSON 요청을 처리 할 수 ​​없다고 말합니다. JSON은 메시지 변환기이라는 것을 가진 Java 오브젝트로 변환됩니다. Spring XML 설정에 <mvc:annotation-driven />이 있거나 Java Config가 활성화 된 경우 JSON 메시지 변환기가 자동으로 등록됩니다. 그렇지 않으면 등록해야합니다.

+0

알렉세이, 당신 말이 맞아요. 고맙습니다. 나는 을 추가했는데 도움이되었다. 그러나 에는 여러 종류가 있습니다 (http://www.springframework.org/schema : 현금, mvc, 작업). 나는 http://www.springframework.org/schema/mvc와 모든 일을 선택했다. – user3233853

+0

미래의 수색자를위한 참고 자료 : Spring mvn은'Content-Type'이'application/x-www-form-urlencoded'라고합니다. 포스터처럼'application/json'으로 설정하는 것이 적절한 방법입니다. – h7r

관련 문제