对Spring MVC Controller的AJAX POST请求无法正常工作

时间:2015-03-21 11:50:39

标签: jquery ajax json spring spring-mvc

我正面临错误:

  

无法加载资源:服务器响应状态为415   (不支持的媒体类型)

我的代码的AJAX部分如下:

$.ajax({ 
    url: '/authentication/editUser',    
    type: "POST", 
    contentType: "application/json",
    data: JSON.stringify(requestObj), //Stringified JSON Object

    success: function(resposeJsonObject) {
       //
    }   
});

控制器的处理程序方法:

@RequestMapping(value = "/editUser", method = RequestMethod.POST, 
    headers = {"Content-type=application/json"})
@ResponseBody
public  EditUserResponse editUserpost(@RequestBody EditUserRequest editUserRequest) {
    System.out.println(editUserRequest);
    return new EditUserResponse();
}

如何解决错误?

4 个答案:

答案 0 :(得分:1)

在AJAX函数的 beforeSend 处理程序中手动设置Content-TypeAccept,并删除spring控制器处理程序方法的标题,使其工作方式如下:

AJAX功能:

$.ajax({
    url: '/authentication/editUser',
    type: 'POST',
    data: JSON.stringify(requestObj), //Stringified Json Object
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json");
    }
    success: function(resposeJsonObject){}
});

和控制器处理程序方法如:

@RequestMapping(value = "/editUser" , method = RequestMethod.POST)
public @ResponseBody EditUserResponse editUserpost(@RequestBody EditUserRequest editUserRequest){
   System.out.println(editUserRequest);
   return new EditUserResponse();
}

另见

答案 1 :(得分:0)

更改您的AJAX通话,添加标题:

headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
}

您的整体AJAX调用应如下所示:

$.ajax({ 
    url: '/authentication/editUser',    
    type: "POST", 
    headers: { 
        'Accept': 'application/json', 
        'Content-Type': 'application/json' 
    }
    dataType: "json",
    data: JSON.stringify(requestObj), //Stringified JSON Object

    success: function(resposeJsonObject) {            
        //
    }
});

Content-Type使用@RequestBody标头来确定发送数据的格式。

答案 2 :(得分:0)

我认为您应该尝试删除控制器中的标头,如下所示:

@RequestMapping(value = "/editUser" , method = RequestMethod.POST)

答案 3 :(得分:0)

尝试这个..我在控制器和jquery中改变了......希望它有效

$.ajax({ 
        url: '/authentication/editUser',    
        type: "POST", 
        contentType: "application/json",
        data: $("#FormName").serialize()

        success: function(respose) {
           //
        }   
    });

控制器的处理程序方法:

  @RequestMapping(value = "/editUser", method = RequestMethod.POST, 
        headers = {"Content-type=application/json"})
// removed @RequestBody 
    @ResponseBody
    public  EditUserResponse editUserpost(EditUserRequest editUserRequest) {
        System.out.println(editUserRequest);
        return new EditUserResponse();
    }