如何用Thymeleaf+Spring Boot接收表单提交的可变长度对象数组?
解决Spring Boot接收可变对象列表参数的问题
问题根源
你当前用@RequestParam("medicamente")接收数组,但前端提交的是medicamente[${index}][medicament]这种对象属性结构化参数,Spring无法将这类参数映射到单纯的数组上,所以抛出参数不存在的错误。
修复方案
1. 修改控制器参数绑定方式
把@RequestParam换成@ModelAttribute(或直接省略,Spring默认会用@ModelAttribute处理对象/列表绑定),直接接收List<MedicamentatieStartStop>类型参数:
public String setNewTratament( @ModelAttribute("medicamente") List<MedicamentatieStartStop> input, Model model) { // 业务逻辑处理 }
若习惯用数组,也可写成MedicamentatieStartStop[] input,效果一致。
2. 确保实体类符合绑定要求
MedicamentatieStartStop类必须包含与前端name对应的属性(比如medicament),同时要有无参构造方法和对应的getter/setter:
public class MedicamentatieStartStop { private String medicament; // 其他对应属性按需添加 // 必须的无参构造方法 public MedicamentatieStartStop() {} // getter和setter方法 public String getMedicament() { return medicament; } public void setMedicament(String medicament) { this.medicament = medicament; } }
3. 确认前端name格式正确性
你用AlpineJS绑定的medicamente[${index}][medicament]格式是可行的,Spring支持这种方括号风格的属性绑定,也可以换成点分隔的格式:
<input x-bind:name="`medicamente[${index}].medicament`" type="text" class="input input-bordered w-full">
两种格式Spring都能正确解析到对象的对应属性上。
额外注意事项
- 若表单为POST提交,确保表单
method设为post,且enctype使用默认的application/x-www-form-urlencoded(仅文件上传场景需用multipart/form-data)。 - 若列表可能为空,可给参数添加
required = false避免空提交报错:
@ModelAttribute("medicamente")(required = false) List<MedicamentatieStartStop> input
内容的提问来源于stack exchange,提问作者Tomi
相关产品推荐
相关产品推荐

