将数据作为Angular JS中的表单数据发布到Java REST Web服务时出现问题

时间:2015-03-27 09:25:03

标签: java angularjs http-post jax-rs

我正在尝试在Java中创建一个Web服务,该服务接受两个列表作为FormData参数。

我使用了this answer中提到的Angualr JS http服务。

var queryRequest = $http({
    method:'POST',
    url:'services/test/testPath',
    data:$.param({"listA":myList1,"listB":myList2}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
});

我的对象myList1

var myList1=[];
var obj={};
obj["val1"]=1
obj["val2"]=2
myList1.push(obj);

我的对象myList2

var myList2=[];

var obj={};
obj["val11"]=3
obj["val12"]=4
myList2.push(obj);

var obj={};
obj["val11"]=5
obj["val12"]=6
myList2.push(obj);

我正在使用javax.ws.rs.*作为其余服务

接受数据的我的Java服务器端点是as-

@Path("testPath")
@POST
@Consumes("application/x-www-form-urlencoded;charset=UTF-8")
@Produces("application/json")
public DataDTO addIssuancesForFP(@FormParam("listA") List<TypeA> list1, @FormParam("listB") List<TypeB> list2) {

    System.out.println("Service is called correctly");
    return service.getDTO(list1,list2);
}

我的classe&#39; TypeA&#39;

 private Integer val1;
 private Integer val2;
 //getters and setters, and default constructor

我的classe&#39; TypeB&#39;

 private Integer val11;
 private Integer val12;
 //getters and setters, and default constructor

端点正确击中,但我在列表中得到null。请求结构是:

  

请求类型

    Accept:application/json, text/plain, */*
    Content-Type:application/x-www-form-urlencoded;charset=UTF-8
  

表格数据

    listA[0][val1]:1
    listA[0][val2]:2

    listB[0][val11]:3
    listB[0][val12]:4
    listB[1][val11]:5
    listB[1][val12]:6

似乎是正确的,我认为错误在服务器部分。如何解决这个问题?

由于

注意:这只是模拟数据,格式完全相同

1 个答案:

答案 0 :(得分:1)

是的,所以我不认为使用表格编码数据会起作用。原因是它主要用于键值对,格式为

key1=value7&key2=value2&key3=value3...

您正在做的只使用两个键,listAlistB。因此,想象一下这些值需要什么样才能发送整个列表。它不漂亮。对于复杂数据,以JSON格式发送数据更为可行。针对您的特定用例的问题在于需要发送两个不相关的对象(或数组)。为此,解决方案是使用multipart。你好运,因为我昨天刚刚发布了一个late answer,关于Angular如何处理这个问题。

我不会在这里解释有关代码的解释。一切都在该链接中解释。当你回答这个问题时,请仔细阅读。我将使用Jersey作为JAX-RS实现(如链接中的示例 - 但它还提供其他替代实现)

资源

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/form")
public class FormResource {

    @POST
    @Consumes("multipart/form-data")
    @Produces("text/plain")
    public String addIssuancesForFP(@FormDataParam("listA") List<TypeA> list1, 
                                     @FormDataParam("listB") List<TypeB> list2) {

        StringBuilder response = new StringBuilder();
        for(TypeA a: list1) {
            response.append(a.toString()).append("; ");
        }

        for (TypeB b: list2) {
            response.append(b.toString()).append("; ");
        }

        System.out.println("Service is called correctly");
        return response.toString();
    }
}

<!DOCTYPE html>
<html ng-app="formApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="js/libs/jquery/jquery.js"></script>
        <script src="js/libs/angular.js/angular.js"></script>
        <script>
            angular.module("formApp", [])
            .controller("defaultCtrl", function($scope, $http) {
                $scope.sendData = function() {
                    var myList1 = [];
                    var obj = {};
                    obj["val1"] = "value1";
                    obj["val2"] = "value2";
                    myList1.push(obj);

                    var myList2 = [];

                    var obj = {};
                    obj["val11"] = "value11";
                    obj["val12"] = "value12";
                    myList2.push(obj);

                    var obj = {};
                    obj["val11"] = "value211";
                    obj["val12"] = "value212";
                    myList2.push(obj);

                    var list1 = JSON.stringify(myList1);
                    var list2 = JSON.stringify(myList2);

                    var boundary = Math.random().toString().substr(2);
                    var header = "multipart/form-data; charset=utf-8; boundary=" + boundary;

                    $http({
                        url: "/api/form",
                        headers: {"Content-Type": header},
                        data: createRequest(list1, list2, boundary),
                        method: "POST"
                    }).then(function(response) {
                        $scope.result = response.data;
                    });

                    function createRequest(list1, list2, boundary) {
                        var multipart = "";
                        multipart += "--" + boundary
                            + "\r\nContent-Disposition: form-data; name=listA"
                            + "\r\nContent-type: application/json"
                            + "\r\n\r\n" + list1 + "\r\n";
                        multipart += "--" + boundary
                            + "\r\nContent-Disposition: form-data; name=listB"
                            + "\r\nContent-type: application/json"
                            + "\r\n\r\n" + list2 + "\r\n";
                            multipart += "--" + boundary + "--\r\n";
                        return multipart;
                    }
                };
             });
        </script>
    </head>
    <body>
        <div ng-controller="defaultCtrl">
            <button ng-click="sendData()">Send</button>
            <p>{{result}}
        </div>
    </body>
</html>

结果

TypeA{val1=value1, val2=value2}; 
TypeB{val1=value11, val2=value12}; 
TypeB{val1=value211, val2=value212};

这是预期的,因为我刚从toString()方法构建了一个字符串,我在TypeATypeB类中实现了这些方法。

public class TypeA {
    public String val1;
    public String val2;
    @Override
    public String toString() {
        return "TypeA{" + "val1=" + val1 + ", val2=" + val2 + '}';
    }
}

public class TypeB {
    public String val11;
    public String val12;
    @Override
    public String toString() {
        return "TypeB{" + "val1=" + val11 + ", val2=" + val12 + '}';
    } 
}

希望这有帮助。