I'm trying to use AngularJS in front end and Resteasy as a Rest API. My problem is that my @FormParam are always null when sending params with AngularsJS.
Here is how my JS :
$scope.addPerson = function(newFirstName, newLastName) {
$http({
method: 'POST',
url: "rest/persons/savePerson",
data: {firstName: 'newFirstName', lastName: 'newLastName'},
headers: {'Content-Type': 'application/json'}
})
.success(function(data) {
alert("DATA : " + data);
}).error(function(data, status, headers, config) {
alert("Could not save new person");
});
};
And this is my code server side :
@POST
@Path("/savePerson")
@Produces("application/json")
@Secured({ "ROLE_USER" })
public PersonBean savePerson(@FormParam("firstName") String firstName,
@FormParam("lastName") String lastName) {
if (firstName== null || lastName== null) {
return null;
}
PersonBean person = personDao.savePerson(firstName,
lastName);
return person ;
}
Any help is appreciated.
You are posting the fields as JSON, not as form encoded data.
headers: {'Content-Type': 'application/json'}
But you can't just change this header. The values will need to be Form encoded. See this page on how to post form data from Angular.
http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm
Although, you may find it better to stick with JSON and let your framework map these fields to a Bean for you.
I haven't used Resteasy but I think it should be as simple as...
@POST
@Path("/savePerson")
@Consumes("application/json")
@Produces("application/json")
@Secured({ "ROLE_USER" })
public PersonBean savePerson(SavePersonBean savePersonBean) {
PersonBean person = personDao.savePerson(savePersonBean.getFirstName(),
savePersonBean.getLastName());
return person;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加