AngularJS http POST到Servlet

时间:2015-07-14 08:29:48

标签: java angularjs servlets

我经历了很多StackOverflow的答案并且搜索了很多但仍然无法找到我的帖子请求无效的原因。

这是我的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> 

这是我的控制者:

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");
    };
});

我的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");
    }

我一直得到这个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)

请告诉我这里我做错了什么。

3 个答案:

答案 0 :(得分:3)

您的请求不包含名为“data”的URL参数,因此request.getParameter(“data”)返回null并且您获得NullPointerException。

您尝试通过URL参数发送Javascript对象,这与非浅层对象不相符。

我建议将数据作为请求有效负载发送:

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

在客户端上,您需要确保将数据作为正确的JSON发送:

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

答案 1 :(得分:0)

我认为您应该将数据发送为

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

注意data : {data: $scope.user}

答案 2 :(得分:0)

您正在使用request.getReader()请求,您的数据将在请求正文中发送 - 而非参数。您需要使用// example using the javax.json.stream package JsonParser parser = Json.createParserFactory().createParser(request.getReader()); 阅读内容。

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            Area area = areas[i][j];
            int width = (int) area.getBounds2D().getWidth();
            int height = (int) area.getBounds2D().getHeight();

            pieces[i][j] = new BufferedImage(width, height, image.getType());
            Graphics2D gr = pieces[i][j].createGraphics();
            gr.setClip(area);
            gr.drawImage(image, 0, 0, null);
            gr.dispose();

            try {
                ImageIO.write(pieces[i][j], "png", new File("img/img" + i + "" + j + ".png"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }