java - org.springframework.web.bind.MissingServletRequestParameterException异常

标签 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服务 Controller 中的映射:

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

    getAnswerDAC().addCorrectAnswer(answerId, correct);

}

最佳答案

@RequestParam 有一个属性required,默认为真。如果不需要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 隐式设置 required 为 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);
}

希望对你有帮助

关于java - org.springframework.web.bind.MissingServletRequestParameterException异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14218868/

相关文章:

java - Ajax查询中Java + Spring的CORS政策错误

java - 如何在 FreeMarker 中调用公共(public) Java 变量

java - 从返回奇怪字符的 URL 读取数据

python - 如何处理 API 请求中的不同响应码?

ios - 如何在 YouTube Search API v3 中获取内容详细信息? ( swift )

java - 如何以编程方式检查某个 URL 是否需要使用 Spring Security 进行身份验证?

java - 使用 TemporalTipe.Time 进行 Query.setparameter

java - 如何修复/学习有助于理解基本方法和类、Java代码和单词问题

json - 如何停止 Pandas Dataframe read_json 方法将我的时代转换为人类可读的字符串

java - 考虑 Spring 中的接口(interface)代码?