使用Ajax进行PUT请求(处理Spring)

时间:2017-05-21 09:24:50

标签: jquery ajax spring rest spring-mvc

我想使用Ajax发送PUT请求。我发送带有必要信息的请求:newNavigation。

PUT请求:

var newNavigation;
var newInputNavigation = document.getElementById('newInputNavigation');
newNavigation = newInputNavigation.value;

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

控制器:

  private final String prefix = "/airline/";

 @RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public String updateFlight(@PathVariable("id") String id, @RequestParam("navigation") String navigation) {
        String returnText = "Flight edited successful";
        String str1 = navigation;
        String str2 = id;
        return returnText;
    }

错误:

 PUT http://localhost:8080/airline/flights/11 400 ()

问题:

如何使用必要的数据发送PUT请求(newNavigation)?

如何在Spring控制器中获取数据(newNavigation)?

修改

添加了NavigationDTO:

public class NavigationDTO implements Serializable{
    public String navigation;
    public NavigationDTO() {
        super();
    }
}

更改了控制器:

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

错误:

PUT http://localhost:8080/airline/flights/8 415 ()

1 个答案:

答案 0 :(得分:1)

@RequestParam("navigation")

RequestParam意味着您的导航是请求标头中的参数,而不是这种情况,导航位于您的有效负载中,因此您需要对其进行反序列化。

Spring使用Jackson,你需要创建一个以导航作为参数的POJO类,该类应该是可序列化的。

在您的方法中使用@RequestBody将已解析的有效负载存储在对象

 public String updateFlight(@PathVariable("id") String id, @RequestBody NavigationDto navigation) { //NavigationDto is the Pojo class

然后您可以轻松地从对象"导航"

访问导航属性