You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot MVC中无需包装类绑定List<List<Boolean>>到请求参数

解决方案:直接获取List<List<Boolean>>作为控制器方法参数

方法一:通过索引命名表单参数(推荐,Spring原生支持)

你当前的问题源于单个hidden input传递整个列表时,Thymeleaf会把列表转为默认的toString()格式(比如[[true,false],[false,true]]),Spring MVC无法直接将这种字符串绑定为嵌套列表。

修改Thymeleaf表单,为每个布尔值生成带索引的hidden input,让Spring自动识别并绑定为嵌套列表:

<div>
    <table>
        <tr th:each="row: ${values}">
            <td th:each="cell: ${row}" th:class="${cell ? 'red' : 'green'}"></td>
    </table>
    <form action="#" method="POST" th:action="@{/step}">
        <!-- 遍历行和单元格,生成带索引的隐藏参数 -->
        <th:block th:each="row, rowStat : ${values}">
            <th:block th:each="cell, cellStat : ${row}">
                <input type="hidden" 
                       th:name="|values[${rowStat.index}][${cellStat.index}]|" 
                       th:value="${cell}">
            </th:block>
        </th:block>
        <input type="submit" value="Submit"/>
    </form>
</div>

此时控制器方法可以直接接收List<List<Boolean>>类型参数,无需手动解析:

@PostMapping("/step")
public String nextStep(@RequestParam List<List<Boolean>> values, Model model) {
    values = gameService.nextStep(values);
    model.addAttribute("values", values);
    return "render";
}

方法二:序列化JSON并配置自动转换

如果不想生成多个hidden input,可以将列表序列化为JSON字符串传递,再配置Spring自动反序列化:

1. 修改Thymeleaf模板,将列表转为JSON字符串

利用Spring容器中的ObjectMapper生成JSON:

<form action="#" method="POST" th:action="@{/step}">
    <input type="hidden" 
           name="values" 
           th:value="${@jacksonObjectMapper.writeValueAsString(values)}">
    <input type="submit" value="Submit"/>
</form>

2. 配置Spring转换器,自动将JSON字符串转为嵌套列表

创建Web配置类,注册自定义转换器:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final ObjectMapper objectMapper;

    // 注入Spring默认的ObjectMapper
    public WebConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, List<List<Boolean>>>() {
            @Override
            public List<List<Boolean>> convert(String source) {
                try {
                    return objectMapper.readValue(source, new TypeReference<List<List<Boolean>>>() {});
                } catch (JsonProcessingException e) {
                    throw new IllegalArgumentException("参数格式错误", e);
                }
            }
        });
    }
}

3. 修改控制器方法

此时控制器可以直接接收List<List<Boolean>>参数:

@PostMapping("/step")
public String nextStep(@RequestParam List<List<Boolean>> values, Model model) {
    values = gameService.nextStep(values);
    model.addAttribute("values", values);
    return "render";
}

内容的提问来源于stack exchange,提问作者Roman Volosiuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:45:35