我正在尝试在前端使用AngularJS而在Resteasy中使用Rest API。 我的问题是,当使用AngularsJS发送params时,我的@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 ;
}
感谢任何帮助。
答案 0 :(得分:4)
您将字段发布为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;
}