Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC @RequestParam - empty List vs null

Tags:

spring-mvc

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?

like image 875
Vojtěch Avatar asked Aug 03 '18 19:08

Vojtěch


People also ask

Can RequestParam be 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.

What is the difference between @RequestParam and ModelAttribute?

@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.

Do @RequestParam has default value?

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.

What is @RequestParam in Spring MVC?

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.


1 Answers

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 = "")
like image 161
Laplie Anderson Avatar answered Oct 17 '22 19:10

Laplie Anderson