4

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.

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just to clarify, he also have to add '@Consumes("application/json")' to the method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.