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

Resteasy @FormParam null when passing params with AngularJS

本文关键字:Resteasy@FormParam null 参数 AngularJS 使用      更新时间:2023-09-26

我正在尝试在前端使用AngularJS,并将Resteasy作为Rest API。我的问题是,当使用AngularsJS发送参数时,我的@FormParam总是为空。

以下是我的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");
            });
        };

这是我的代码服务器端:

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

感谢您的帮助。

您将字段发布为JSON,而不是表单编码数据。

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

但你不能只改变这个标题。这些值需要进行Form编码。请参阅本页,了解如何从Angular发布表单数据。

http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

尽管如此,您可能会发现更好的做法是坚持使用JSON,并让您的框架为您将这些字段映射到Bean。

我没有使用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;
}