【问题标题】:Sending Json Data to Spring Controller将 Json 数据发送到 Spring 控制器
【发布时间】:2018-01-18 16:03:01
【问题描述】:

我正在尝试将 json 数据从 angular post 发送到 spring 控制器,但在控制台中得到 404:

发布 http://localhost:8080/app/orderDetails/saveOrder/[object%20Object],[object%20Object] 404(未找到)

JS

var i=0;
var j = ngCart.getCart().items.length;
$scope.list=[];
for(i;i<j;i++){
    $scope.list.push({
          'id': ngCart.getCart().items[i]._id,
          'quantity':ngCart.getCart().items[i]._quantity
        });
    }
 $http.post("/app/orderDetails/saveOrder/"+$scope.list) 

Java(弹簧)

@RequestMapping(value = "/saveOrder/list",headers="Accept=application/json")

public @ResponseBody Object saveOrder(@PathVariable List list){
}   

【问题讨论】:

标签: java angularjs json spring spring-mvc


【解决方案1】:

您不能将List 用作PathVariable。改为 RequestBody 并修复您的 JS 代码以将 $scope.list 作为正文发送,而不是将其附加到 url:

-$http.post("/app/orderDetails/saveOrder/"+$scope.list)
+$http.post("/app/orderDetails/saveOrder", $scope.list); 

还创建一个带有 id 和 quantity 字段的包装器对象,类似于:

public class CartItem {
    private Long id;
    private Long quantity;
    //getters and setters
}

然后你就可以用这个对象参数化你的List:

- public @ResponseBody Object saveOrder(@PathVariable List list){
+ public @ResponseBody Object saveOrder(@RequestBody List<CartItem> list){

【讨论】:

  • 只是一个建议,但我还要补充一点,@PathVariable 正在寻找/寻找/a/path 与正文中的对象
  • @Brian 是的,如果对“POST”和“PUT”操作都使用相同的方法是个好主意。它被映射为所有操作,但有些东西告诉我它仅用于“POST”。
【解决方案2】:

您应该将 @PathVariable 替换为 @Request Body 并修复您的 js 代码以将列表作为请求正文的一部分发送(而不是将其添加到路径中)。

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2013-01-11
    相关资源
    最近更新 更多