问题
I am trying to post my form data to my rest service using angular js and jersey. However the bean received at the rest service is null. Following is my angular code for the POST request.
(function() {
var dataUrls = {
addSurveyUrl : '/CompanySurveyPortal/Company/Surveys/addSurvey'
}
angular.module('addNewSurvey', []).service('addSurveyDataService',
function($http) {
this.addNewSurvey = function(survey)
{
return $http.post(dataUrls.addSurveyUrl, {"surveyId": survey.surveyId, "title": survey.question, "choice1": survey.firstOption, "choice2": survey.secondOption ,"status": 'Open'});
};
})
.controller('AddNewSurveyController', function($scope, $log, responseDataService, $stateParams, $state, $filter, $rootScope, addSurveyDataService){
this.survey = {};
this.addSurvey = function(){
addSurveyDataService.addNewSurvey(this.survey);
};
function init(){
}
init();
})
})();
The data from the form is successfully populated in the $http.post statement. The bean at the method to consume the request is however null each time.
@POST
@Path("addSurvey")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_JSON)
public void addNewSurvey(@BeanParam Survey survey,
@Context HttpServletResponse servletResponse) throws IOException,
SQLException {
SurveyDao surveyDao = new SurveyDao();
surveyDao.addSurvey(survey);
}
回答1:
The main problem I see, is the incorrect use of @BeanParam. This should only be used for cases where you want to combine different @XxxParam annotated params into a POJO, like
public class Survey {
@FormParam("id")
public String id;
@FormParam("title")
public String title;
}
Then @BeanParam would work, given the data is actually coming in application/x-www-form-urlencoded. But your request is actually coming in as JSON, which means that the request is not being converted to the Survey
If you simply remove the @BeanParam, and you have a JSON provider registered, it should work.
来源:https://stackoverflow.com/questions/29590124/angular-js-post-object-to-jersey-is-null