简体   繁体   English

使用AngularJS传递params时,Resteasy @FormParam为null

[英]Resteasy @FormParam null when passing params with AngularJS

I'm trying to use AngularJS in front end and Resteasy as a Rest API. 我正在尝试在前端使用AngularJS而在Resteasy中使用Rest API。 My problem is that my @FormParam are always null when sending params with AngularsJS. 我的问题是,当使用AngularsJS发送params时,我的@FormParam总是为null。

Here is how my JS : 这是我的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. 您将字段发布为JSON,而不是表单编码数据。

headers: {'Content-Type': 'application/json'}

But you can't just change this header. 但你不能只改变这个标题。 The values will need to be Form encoded. 这些值需要进行Form编码。 See this page on how to post form data from Angular. 请参阅此页面,了解如何从Angular发布表单数据。

http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm 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. 虽然,您可能会发现最好坚持使用JSON并让您的框架将这些字段映射到Bean。

I haven't used Resteasy but I think it should be as simple as... 我没有使用Resteasy,但我认为它应该像......一样简单

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM