如何发送json文件抛出POST方法并在servlet上接收它

How to send json file throw POST method and recive it on the servlet

本文关键字:servlet 方法 json 何发送 文件 POST      更新时间:2023-09-26

我正在尝试发送一个json对象,如:{id: 1, firstName: Paul, lastName: Lambert}

问题是我在json对象上得到了一个NULL或错误的参数

testProjectApp.factory('updateClient', function($http, $q) {
    return {
        postClient: function (clientData) {
            var deferred = $q.defer();
            alert(clientData.firstName);
            $http({
                url: 'UpdateClient',
                method: "POST",
                contentType: 'application/json',
                data: JSON.stringify(clientData)
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).error(function (data, status, headers, config) {
                deferred.reject(status);
            });
            return deferred.promise;
        }
    };
});

在servlet中:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject json;
    try {
        System.out.println(request.getParameter("data"));
        json=new JSONObject(request.getReader());
        ....

无需执行data: JSON.stringify(clientData)。Angular将自动格式化为JSON。

控制器代码:

    function updateClient($scope, $http) {
    $scope.client = {};
    $scope.clientUpdate = function() {
        $http({
            method : 'POST',
            url : '/UpdateClient',
            data : $scope.client
        }).success(function(data) {
           // do something if the request is success
        }).error(function(data) {
           // do something if the request is fail
        });
    }

Servlet代码:

JSONObject jsnObjt = new JSONObject(request.getParameter("data"));
Iterator it = jsnObjt.keys(); 
while(it.hasNext())
{
    String key = it.next(); 
    Object ob = jsnObjt.get(key); 
    String user = jsnObjt.get("client");
}

关于您的需求的示例HTML:

<form ng-controller="updateClient" ng-submit="clientUpdate()">
    <input type="text" id="id" name="id" ng-model="client.id">
    <input type="text" id="fname" name="fname" ng-model="client.firstName"> 
    <input type="text" id="lname" name="lname" ng-model="client.lastName">
    <button type="submit" class="btn">Update</button>
</form>