Spring mvc Spring MVC@RequestParam-空列表vs null

Spring mvc Spring MVC@RequestParam-空列表vs null,spring-mvc,Spring Mvc,默认情况下,Spring MVC假定需要@RequestParam。考虑这种方法(在Kotlin): 但是,在这种情况下,由于列表是空的,因此无法序列化空列表,因此该参数基本上消失,因此不满足关于必需参数的条件。必须在@RequestParam注释上使用required:false。这并不好,因为我们永远不会收到空列表,而是空列表 有没有办法强迫Spring MVC在这种情况下总是假定空列表,而不是null?尝试过这种方法 fun myMethod(@RequestParam list: Lis

默认情况下,Spring MVC假定需要
@RequestParam
。考虑这种方法(在Kotlin):

但是,在这种情况下,由于列表是空的,因此无法序列化空列表,因此该参数基本上消失,因此不满足关于必需参数的条件。必须在
@RequestParam
注释上使用
required:false
。这并不好,因为我们永远不会收到空列表,而是空列表

有没有办法强迫Spring MVC在这种情况下总是假定空列表,而不是
null

尝试过这种方法

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

您可以在控制器中尝试WebDataBinder

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

这可以通过ObjectMapper在序列化中进行管理。如果您在spring MVC中使用jackson,您可以执行以下任一操作

1) 配置对象映射器:

objectMapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);
2) 或者,如果您正在通过xml配置使用bean:

<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>
</bean>

写入空的JSON数组

要让Spring为您提供一个空列表,而不是
null
,请将默认值设置为空字符串:

@RequestParam(required = false, defaultValue = "")

这是我尝试的第一件事。Spring使用的反射不能用默认值处理。这怎么样?@RequestParam(“list”,required=false,defaultValue=listOf())如果您尝试过,您会知道它甚至无法编译。我正在寻找一个通用的解决方案,意思是不在单个控制器中。您可以将此
@InitBinder
方法放在带有
@ControllerAdvise
注释的类中,而不是放在控制器中。然后它将应用于所有控制器。这似乎使列表为空,而不是如上所述的空列表。
<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>
</bean>
@RequestParam(required = false, defaultValue = "")