Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC - HTTP status code 400 (Bad Request) for missing field which is defined as being not required

I have Spring MVC application with this controller method.

@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

HTTP Status 400 - Required Long parameter 'number' is not present

although the controller method annotation clearly defines the "number"-parameter as not required.

Does anyone have a slight idea of what could be going on?

Thank you.

PS: The exception that is being thrown is as follows:

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.

like image 795
AlexLiesenfeld Avatar asked Jul 25 '13 12:07

AlexLiesenfeld


2 Answers

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.

like image 146
Yohan Liyanage Avatar answered Sep 28 '22 04:09

Yohan Liyanage


My problem was that some of the headers in a request I was sending with Postman were not present (were unchecked):

enter image description here

When I checked back the Content-Length header, the request worked fine (200 OK response).

like image 31
parsecer Avatar answered Sep 28 '22 03:09

parsecer