Spring MVC - 缺失字段的 HTTP 状态代码 400(错误请求)被定义为不需要
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17858537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC - HTTP status code 400 (Bad Request) for missing field which is defined as being not required
提问by AlexLiesenfeld
I have Spring MVC application with this controller method.
我有带有此控制器方法的 Spring MVC 应用程序。
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addNumber(@RequestParam(value="number", required=false) Long number) {
...
return "redirect:/showAll/";
}
In my JSP I have a standard HTML form which is posting a value named "number" to the controller method above. However, if I leave out the value (do not enter anything into the text field) and POST the data to the controller, before the controller method is called my browser shows
在我的 JSP 中,我有一个标准的 HTML 表单,它向上面的控制器方法发布了一个名为“number”的值。但是,如果我省略了值(不要在文本字段中输入任何内容)并将数据发布到控制器,则在调用控制器方法之前,我的浏览器会显示
HTTP Status 400 - Required Long parameter 'number' is not present
although the controller method annotation clearly defines the "number"-parameter as notrequired.
尽管控制器方法注解清楚地定义了“数字” -parameter作为不必需的。
Does anyone have a slight idea of what could be going on?
有没有人对可能发生的事情有一点想法?
Thank you.
谢谢你。
PS: The exception that is being thrown is as follows:
PS:抛出的异常如下:
org.springframework.web.bind.MissingServletRequestParameterException: Required Long parameter 'number' is not present
EDIT: This is a Spring 3.2.3.RELEASE bug ( see here). With version 3.1.4.RELEASE I do not have this problem anymore.
编辑:这是一个 Spring 3.2.3.RELEASE 错误(见这里)。使用版本 3.1.4.RELEASE 我不再有这个问题了。
回答by Yohan Liyanage
I came across the same situation, and this happens when your parameter is present in the request with an empty value.
我遇到了同样的情况,当您的参数存在于具有空值的请求中时,就会发生这种情况。
That is, if your POST body contains "number=" (with empty value), then Spring throws this exception. However, if the parameter is not present at all in the request, it should work without any errors.
也就是说,如果您的 POST 正文包含“number=”(值为空),则 Spring 会抛出此异常。但是,如果请求中根本不存在该参数,则它应该可以正常工作而不会出现任何错误。

