Monday, August 13, 2018

Spring MVC @RequestParam - empty List vs null

Leave a Comment

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?

4 Answers

Answers 1

This can be managed in the serialization with ObjectMapper. If you are using jackson in your spring MVC, you can do either the following.

  • Configure your object mapper.
    objectMapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);  
  • Or if you are using beans via xml config. <bean name="objectMapper" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean" autowire="no"> <property name="featuresToDisable"> <list> <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_EMPTY_JSON_ARRAYS</value> </list> </property>

Answers 2

Tried this?

fun myMethod(@RequestParam list: List<String> = listOf()) { ... } 

Answers 3

You can try a WebDataBinder in your controller.

@InitBinder public void initBinder(WebDataBinder binder) {     binder.registerCustomEditor(List.class, "list", new CustomCollectionEditor( List.class, true)); } 

Answers 4

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 Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment