简体   繁体   English

AngularJS http POST到Servlet

[英]AngularJS http POST to Servlet

I went through a lot of StackOverflow answers and googled a lot but still could not find why my post request is not working. 我经历了很多StackOverflow的答案并搜索了很多但仍无法找到我的帖子请求无效的原因。

This is my jsp: 这是我的jsp:

<div class="container">
      <form class="form-signin" ng-controller="MyController">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="username" class="sr-only">Username</label>
        <input type="text" id="username"  ng-model="user.name" class="form-control" placeholder="Username" required autofocus>
        <label for="password" class="sr-only">Password</label>
        <input type="password" ng-model="user.password" id="password" class="form-control" placeholder="Password" required>
        <button class="btn btn-lg btn-primary btn-block" ng-click="login()" type="submit">Sign in</button>
      </form>
    </div> 

This is my controller: 这是我的控制器:

app.controller('MyController', function($scope, $http) {

    $scope.login = function() {
        console.log($scope.user);
        $http({
            method : 'POST',
            url : 'login',
            data : $scope.user,
            headers: {
                'Content-Type': 'application/json'
            }
        }).success(function(data) {
            console.log(data);
        }).error(function(data) {
            console.log(data);
        });
        console.log("POST done");
    };
});

And my servlet: 而我的servlet:

protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        System.out.println("inside do POST");
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonObject obj = (JsonObject) parser
                .parse(request.getParameter("data"));
        Iterator it = (Iterator) obj.entrySet();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        System.out.println("over");
    }

I keep getting this Null pointer exception 我一直得到这个Null指针异常

java.lang.NullPointerException
    at java.io.StringReader.<init>(StringReader.java:50)
    at com.google.gson.JsonParser.parse(JsonParser.java:45)
    at com.zookeeperUI.controller.Login.doPost(Login.java:40)

Please tell me what am I doing wrong here . 请告诉我这里我做错了什么。

Your request does not contain a URL parameter named "data", therefore request.getParameter("data") returns null and you get the NullPointerException. 您的请求不包含名为“data”的URL参数,因此request.getParameter(“data”)返回null并且您获得NullPointerException。

You try to send a Javascript object via URL parameters which does not go well with non-shallow objects. 您尝试通过URL参数发送Javascript对象,这与非浅层对象不相符。

I would recommend to send the data as request payload: 我建议将数据作为请求有效负载发送:

JsonObject obj = (JsonObject) parser.parse(request.getReader());

On the client you need to make sure that your data is sent as proper JSON: 在客户端上,您需要确保将数据作为正确的JSON发送:

$http({
        method : 'POST',
        url : 'login',
        contentType: 'application/json',
        data : JSON.stringify($scope.user),
    })...

i think you should be sending data as 我认为你应该发送数据

$http({
    method : 'POST',
    url : 'login',
    data : {data: $scope.user},
    headers: {
        'Content-Type': 'application/json'
    }
}).success(function(data) {
    console.log(data);
});

pay attention to data : {data: $scope.user} 注意data : {data: $scope.user}

You are using a POST request and your data is sent in the request body - not as parameter . 您正在使用POST请求,您的数据将在请求正文中发送 - 而不是作为参数 You need to read the content using request.getReader() . 您需要使用request.getReader()读取内容。

// example using the javax.json.stream package
JsonParser parser = Json.createParserFactory().createParser(request.getReader());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM