代码之家  ›  专栏  ›  技术社区  ›  Vojtěch

Spring MVC@RequestParam-空列表vs空

  •  5
  • Vojtěch  · 技术社区  · 6 年前

    默认情况下,Spring MVC假设 @RequestParam 是必需的。考虑这个方法(在Kotlin中):

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

    当从javaScript传递空列表时,我们将调用如下内容:

    $.post("myMethod", {list: []}, ...)
    

    但是,在这种情况下,由于列表是空的,因此无法序列化空列表,因此参数实际上会消失,因此不满足所需参数的条件。一个人被迫使用 required: false @请求参数 注解。这不太好,因为我们永远不会收到空列表,而是空列表。

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

    4 回复  |  直到 6 年前
        1
  •  12
  •   Laplie Anderson    6 年前

    让Spring给你一个空列表而不是 null ,则将默认值设置为空字符串:

    @RequestParam(required = false, defaultValue = "")
    
        2
  •  2
  •   Adam Michalik    5 年前

    这可以用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>
    
        3
  •  0
  •   Anders Mikkelsen    6 年前

    试过了吗?

    fun myMethod(@RequestParam list: List<String> = listOf()) { ... }
    
        4
  •  0
  •   Johna    6 年前

    您可以在控制器中尝试WebDataBinder。

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