org.springframework.web.HttpMediaTypeNotSupportedException:内容类型' application / json'不支持(Ajax,Spring)

时间:2017-05-21 11:38:59

标签: java json ajax spring spring-mvc

我尝试发送PUT请求。我有 serialazible class 和带有必要设置的控制器,我的请求有 contentType:" application / json "。

FlightDto:

 public class FlightDto implements Serializable {
    private int id;
    private String navigation;

    public FlightDto() {
        super();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNavigation() {
        return navigation;
    }

    public void setNavigation(String navigation) {
        this.navigation = navigation;
    }

}

PUT请求:

  function editNavigation() {
    var flight={
        id:idAction.replace('edit',''),
        navigation:newNavigation
    };
    console.log(flight);
    var prefix = '/airline/';
    $.ajax({
        type: 'PUT',
        url: prefix +'flights/' + idAction.replace('edit',''),
        data: JSON.stringify(flight),
        contentType: "application/json",
        success: function(receive) {
            $("#adminTable").empty();
            $("#informationP").replaceWith(receive);
            $("#hiddenLi").removeAttr('style');
        },
        error: function() {
            alert('Error edited flight');
        }
    });
}

的console.log(飞行); - 对象{id:" 7",导航:" sdfdsfsd"}

FlightController:

   @RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String updateFlight(@PathVariable("id") String id, @RequestBody FlightDto flightDto) {
        String returnText = "Flight edited successful";
        String str1 = flightDto.getNavigation();
        String str2 = id;
        return returnText;
    }

错误:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

如何修复此错误?

1 个答案:

答案 0 :(得分:0)

您需要使用标头属性

在标头中定义不在有效内容中的内容类型
   data: JSON.stringify(flight),
   headers:{contentType: "application/json"}