如何在Thymeleaf表格中编辑List数据?绑定异常排查
Thymeleaf表单绑定问题排查与解决
我把List数据传入Model后,用th:each="userDTO : ${usersDTO}"遍历数据,接着尝试在表格内通过<form th:object="${userDTO}">直接编辑数据。使用th:field="*{firstName}"时完全不生效,但换成th:value能正常显示数据。运行时还抛出了ParseException和IllegalStateException: Neither BindingResult nor plain target object for bean name 'userDTO' available as request attribute异常。
相关代码片段:
<td th:text="${userDTO.id}"></td> <td><input type="text" id="firstName" th:field="*{firstName}"></td> <td><input type="text" id="lastName" th:field="*{lastName}"></td> <td><input type="email" id="email" th:field="*{email}"></td> <td> <button type="submit">Save</button> </td> </form>
问题原因及解决方法:
- 核心问题:Thymeleaf的
th:object要求绑定的对象必须是Spring MVC上下文中的请求属性(即通过model.addAttribute()传入的单个对象),而th:each遍历出的userDTO是局部变量,并非请求属性,因此th:field无法通过*{}表达式找到绑定对象。 - 解决方案1:通过请求参数传递更新
遍历的时候为每个用户表单添加隐藏ID字段,提交时后端根据ID从List中定位对象并更新。示例代码调整:
后端直接用<form th:action="@{/updateUser}" method="post"> <input type="hidden" th:value="${userDTO.id}" name="id"> <td th:text="${userDTO.id}"></td> <td><input type="text" name="firstName" th:value="${userDTO.firstName}"></td> <td><input type="text" name="lastName" th:value="${userDTO.lastName}"></td> <td><input type="email" name="email" th:value="${userDTO.email}"></td> <td><button type="submit">Save</button></td> </form>UserDTO对象或单独参数接收数据,再根据ID完成更新。 - 解决方案2:绑定整个List集合
将usersDTO作为请求属性传入后,遍历通过索引绑定List中的元素,让th:field能识别对应对象。示例:
后端传入:model.addAttribute("usersDTO", userList);
前端代码:
后端接收时用<form th:object="${usersDTO}" th:action="@{/updateUsers}" method="post"> <tr th:each="user, stat : ${usersDTO}"> <td th:text="${user.id}"></td> <td><input type="text" th:field="*{[__${stat.index}__].firstName}"></td> <td><input type="text" th:field="*{[__${stat.index}__].lastName}"></td> <td><input type="email" th:field="*{[__${stat.index}__].email}"></td> <td><button type="submit">Save</button></td> </tr> </form>@ModelAttribute("usersDTO") List<UserDTO> usersDTO参数即可批量获取更新后的数据。 - 额外注意:如果要单独绑定单个
userDTO,需要在请求时将该对象作为请求属性传入(比如编辑时传入指定用户对象),但这种方式不适合批量遍历编辑的场景。
内容的提问来源于stack exchange,提问作者Viacheslav Kucheruk
相关产品推荐
相关产品推荐

