如何在Spring Boot Controller中更便捷地获取1到20个checkbox的选中值?
高效接收选中checkbox值的实现方案
方案1:统一checkbox name属性+后端List接收(推荐)
先改造前端Thymeleaf代码,将动态变化的checkbox name改为固定值,同时添加value属性绑定poi的唯一标识:
<div> <ul> <li th:each="poi : ${poiList}"> <label th:for="${poi.modelName}" th:text="${poi.modelName}">modelName</label> <input type="checkbox" th:id="${poi.modelName}" th:name="selectedPois" th:value="${poi.modelName}" th:checked="false"/> </li> </ul> </div>
改造后提交的参数格式为selectedPois=poi6&selectedPois=poi15,后端直接用List接收即可,无需逐个声明参数:
@PostMapping("/add") public String save(@RequestParam List<String> selectedPois){ // selectedPois中直接存储所有被选中的poi的modelName,不需要额外判断非空 // 后续逻辑处理 }
方案2:无需修改前端,用Map批量接收参数
如果不方便调整前端代码,可以直接用Map接收所有请求参数,筛选出值为on的参数即可得到选中的poi:
@PostMapping("/add") public String save(@RequestParam Map<String, String> allParams){ List<String> selectedPois = allParams.entrySet().stream() .filter(entry -> "on".equals(entry.getValue())) .map(Map.Entry::getKey) .toList(); // 后续逻辑处理 }
内容的提问来源于stack exchange,提问作者ringhiosi
相关产品推荐
相关产品推荐

