Thymeleaf中th:each循环内使用th:field绑定数据报错如何解决?
错误原因
报错的核心是Thymeleaf表单的th:object绑定逻辑错误:你给th:object绑定的${question}本身就是ArrayList<ExamModel>类型的集合,而你在th:field中写*{question[__${i.index}__].answer},相当于尝试从ArrayList类本身读取名为question的属性,ArrayList不存在这个属性,因此抛出属性找不到的异常。
修复方案
方案1:最小改动(仅修改前端代码)
无需调整后端逻辑,直接去掉th:field里多余的question前缀即可,因为*{}的作用域已经是th:object绑定的ArrayList集合本身,直接用索引访问元素即可:
<form th:action="@{/getresult}" th:object="${question}" method="post"> <table> <tr th:each="q, i: ${question}"> <td th:text="${q.question}"></td> <td><input type="text" th:field="*{[__${i.index}__].answer}" value="answer"/></td> </tr> </table> <input type="submit" value="Result"> </form>
注意:提交表单的POST接口需要对应接收参数,写法参考:
@PostMapping("/getresult") public String getResult(@ModelAttribute("question") List<ExamModel> answerList){ // 业务处理逻辑 return "result"; }
方案2:表单包装类(更规范,适合后续扩展)
如果后续表单需要增加其他字段,建议单独封装表单类,避免直接绑定集合带来的兼容性问题:
- 新建表单包装类
public class ExamForm { private List<ExamModel> questionList; // 生成public的getter、setter方法 }
- 修改GET接口返回包装类
@GetMapping(value="/generateexam") public String generateExam(Model model){ ExamForm examForm = new ExamForm(); examForm.setQuestionList(examService.generateQuestion()); model.addAttribute("examForm", examForm); return "exam"; }
- 修改前端代码绑定包装类
<form th:action="@{/getresult}" th:object="${examForm}" method="post"> <table> <tr th:each="q, i: *{questionList}"> <td th:text="${q.question}"></td> <td><input type="text" th:field="*{questionList[__${i.index}__].answer}" value="answer"/></td> </tr> </table> <input type="submit" value="Result"> </form>
- POST接口直接接收包装类
@PostMapping("/getresult") public String getResult(@ModelAttribute ExamForm examForm){ List<ExamModel> answerList = examForm.getQuestionList(); // 业务处理逻辑 return "result"; }
额外注意
请确认ExamModel类的question、answer字段的getter、setter方法为public,且命名符合JavaBean规范(getQuestion()、setQuestion()、getAnswer()、setAnswer()),避免反射读取属性失败。
内容的提问来源于stack exchange,提问作者Nikko Wasawas
相关产品推荐
相关产品推荐

