org.springframework.web.bind.MissingServletRequestParameterException

时间:2013-01-08 15:51:36

标签: java json spring spring-mvc angularjs

在向服务器端发送呼叫时遇到问题

异常堆栈跟踪:

"org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'answerId' is not present\r\n\tat org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:773)\r\n\tat org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:509)

controller.js

中的Javascript调用
$scope.saveCorrectAnswer = function(answerId) {

        var answerIdVal = 0;
        answerIdVal = answerId;
        if(document.getElementById(answerId).className == 'ico-white-check') {
            $scope.answer.correct = 'Y';
        } else{
            $scope.answer.correct = 'N';
        }

        Answer.update({answerId: answerIdVal, correct: $scope.answer.correct}, function(response) {
            // On success go to Exchange
            //$route.reload();
        },

在java中的服务控制器中进行映射:

@RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
@ResponseBody
public void addCorrectAnswer(@RequestParam int answerId, @RequestParam String correct) {

    getAnswerDAC().addCorrectAnswer(answerId, correct);

}

1 个答案:

答案 0 :(得分:-1)

@RequestParam有一个属性 required ,默认情况下为true。如果不需要answerId,请更改注释和参数类型,如下所示...

@RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
@ResponseBody
public void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) {
     getAnswerDAC().addCorrectAnswer(answerId, correct);
}

编辑:由于answerId是示例中的原始值,因此您还需要在注释中提供defaultValue。提供一个defaultValue隐式设置为false,所以我将其排除在示例...

之外
@RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
@ResponseBody
public void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) {
     getAnswerDAC().addCorrectAnswer(answerId, correct);
}

希望这有帮助