java - Angular http POST to Servlet -


i went through lot of stackoverflow answers , googled lot still not find why post request not working.

this 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 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 servlet:

protected void dopost(httpservletrequest request,             httpservletresponse response) throws servletexception, ioexception {          system.out.println("inside post");         gson gson = new gson();         jsonparser parser = new jsonparser();         jsonobject obj = (jsonobject) parser                 .parse(request.getparameter("data"));         iterator = (iterator) obj.entryset();         while (it.hasnext()) {             system.out.println(it.next());         }         system.out.println("over");     } 

i keep getting null pointer exception

java.lang.nullpointerexception     @ java.io.stringreader.<init>(stringreader.java:50)     @ com.google.gson.jsonparser.parse(jsonparser.java:45)     @ com.zookeeperui.controller.login.dopost(login.java:40) 

please tell me doing wrong here .

your request not contain url parameter named "data", therefore request.getparameter("data") returns null , nullpointerexception.

you try send javascript object via url parameters not go non-shallow objects.

i recommend send data request payload:

jsonobject obj = (jsonobject) parser.parse(request.getreader()); 

on client need make sure data sent proper json:

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

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -