Reputation: 155
I am trying to post query parameters from angular JS to rest server. But the value received in the rest is always null. Can anyone please tell what i am missing?
Angular code,
$http({
method : 'POST',
url : '/rest/user/changePassword',
data : {'id':$scope.user.id, 'password':$scope.user.password, 'newpassword':$scope.user.newpassword},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(' data ');
});
Rest code,
@Path("/changePassword")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response changePassword(@QueryParam("id") int id,
@QueryParam("password") String password,
@QueryParam("newpassword") String newpassword, @Context UriInfo request) {
System.out.println(" id " + id + " re " + request.getQueryParameters().getFirst("id"));
System.out.println(" password " + password + " "+ request.getQueryParameters().getFirst("password"));
System.out.println(" newpassword " + newpassword + " " + request.getQueryParameters().getFirst("newpassword") );
return new Response('asd');
}
I tried $.param in angular side, tried to get parameters from HttpServletRequest but the result is always null.
Upvotes: 3
Views: 5640
Reputation: 64039
Since you are using HTTP POST, you need to replace @QueryParam
with @FormParam
. Your code would then be:
@Path("/changePassword")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response changePassword(@FormParam("id") int id,
@FormParam("password") String password,
@FormParam("newpassword") String newpassword, @Context UriInfo request) {
System.out.println(" id " + id + " re " + request.getQueryParameters().getFirst("id"));
System.out.println(" password " + password + " "+ request.getQueryParameters().getFirst("password"));
System.out.println(" newpassword " + newpassword + " " + request.getQueryParameters().getFirst("newpassword") );
return new Response('asd');
}
Check out this tutorial
You also need to force AngularJS to POST the data as form parameters like so:
$http({
method : 'POST',
url : '/rest/user/changePassword',
data : $.param({
'id' : $scope.user.id,
'password' : $scope.user.password,
'newpassword' : $scope.user.newpassword
}),
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function (data) {
console.log(' data ');
});
Check out this SO answer.
The way your code used the $http object forces angular to post a json object
Upvotes: 1
Reputation: 1887
@QueryParam is used to pick up values passed across in a query string in Get Requests.
Create a Java Object that has the variables matching your data structure, and use that as an input instead of the separate variables.
Upvotes: 1