By default Spring MVC assumes @RequestParam
to be required. Consider this method (in Kotlin):
fun myMethod(@RequestParam list: List<String>) { ... }
When passing empty list from javaScript, we would call something like:
$.post("myMethod", {list: []}, ...)
In this case however, as the list is empty, there is no way to serialize empty list, so the parameter essentially disappears and so the condition on required parameter is not satisfied. One is forced to use the required: false
on the @RequestParam
annotation. That is not nice, because we will never receive the empty list, but null.
Is there a way to force Spring MVC always assume empty lists in such case instead of being null
?
Method parameters annotated with @RequestParam are required by default. will correctly invoke the method. When the parameter isn't specified, the method parameter is bound to null.
@RequestParam is best for reading a small number of params. @ModelAttribute is used when you have a form with a large number of fields. @ModelAttribute gives you additional features such as data binding, validation and form prepopulation.
The default value of the @RequestParam is used to provide a default value when the request param is not provided or is empty. In this code, if the person request param is empty in a request, the getName() handler method will receive the default value John as its parameter.
In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.
To get Spring to give you an empty list instead of null
, you set the default value to be an empty string:
@RequestParam(required = false, defaultValue = "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With