视图到控制器无法传对象:ModeWrapper中modeList为空求助
问题:Thymeleaf提交表单时,Wrapper中的List接收为空?
我希望将对象从视图传递到控制器,但调试时
saveMode方法中wrapper内的modeList为空,想请教问题出在哪里?
重要提示:浏览器表格中已显示modeList的对象。Mode为实体类。
你的现有代码
前端代码
<table class="table table-bordered table-hover table-sm"> <thead class="thead-default"> <tr> <th th:text="stat"></th> <th th:text="Mode"></th> <th th:text="'In use'"></th> </tr> </thead> <tbody> <form th:action="@{/editMode}" method="post"> <tr th:each="mode, stat : ${wrapper.modeList}"> <td th:text="${stat}"></td> <td><input type="text" id="actAs" name="actAs" th:value="${mode.actAs}"/></td> <td><input type="checkbox" name="inUse" th:value="true" th:checked="${mode.inUse}"/></td> </tr> <input type="submit" name="btnSaveMode" value="Zapisz" class="btn btn-outline-success"/> </form> </tbody> </table>
后端代码
@RequestMapping("/") public String index(Model model) { List<Mode> modeList = modeService.findAll(); ModeWrapper wrapper = new ModeWrapper(); wrapper.setModeList(modeList); model.addAttribute("wrapper", wrapper); return "index"; } @RequestMapping(value="/editMode", method = RequestMethod.POST, params = "btnSaveMode") public ModelAndView saveMode(@ModelAttribute("wrapper") ModeWrapper wrapper, BindingResult errors) { return new ModelAndView("redirect:/"); }
ModeWrapper类
public class ModeWrapper { private List<Mode> modeList; public List<Mode> getModeList() { return modeList; } public void setModeList(List<Mode> modeList) { this.modeList = modeList; } }
问题原因
你现在的表单字段name属性只是简单的actAs、inUse,Spring MVC无法将这些零散的字段关联到ModeWrapper里的modeList集合中。要让Spring正确绑定集合类型的参数,必须在表单字段的name中明确指定集合的索引位置,这样Spring才能知道每个输入框对应集合中的哪一个Mode对象。
解决方案
修改前端表单中input的name属性,通过Thymeleaf的循环索引stat.index来标记集合元素的位置,同时处理checkbox的特殊绑定问题:
<table class="table table-bordered table-hover table-sm"> <thead class="thead-default"> <tr> <th th:text="stat"></th> <th th:text="Mode"></th> <th th:text="'In use'"></th> </tr> </thead> <tbody> <form th:action="@{/editMode}" method="post"> <tr th:each="mode, stat : ${wrapper.modeList}"> <td th:text="${stat.index}"></td> <!-- 修改name为modeList[索引].actAs,让Spring识别对应集合元素的属性 --> <td><input type="text" th:id="'actAs_' + ${stat.index}" th:name="|modeList[${stat.index}].actAs|" th:value="${mode.actAs}"/></td> <td> <!-- checkbox需要特殊处理:未勾选时浏览器不会提交值,所以添加同名hidden input提交false --> <input type="checkbox" th:name="|modeList[${stat.index}].inUse|" th:value="true" th:checked="${mode.inUse}"/> <input type="hidden" th:name="|modeList[${stat.index}].inUse|" th:value="false"/> </td> </tr> <input type="submit" name="btnSaveMode" value="Zapisz" class="btn btn-outline-success"/> </form> </tbody> </table>
额外注意事项
- 确保你的
Mode实体类拥有所有属性的getter和setter方法,Spring MVC需要通过这些方法来完成属性的赋值。 - 如果
Mode中有其他复杂属性,也要按照同样的格式绑定(比如modeList[${stat.index}].otherProperty)。
这样修改后,当你提交表单时,Spring就能正确地将每个行的输入值封装到ModeWrapper的modeList集合中,调试时就能看到数据了。
内容的提问来源于stack exchange,提问作者enyoucky
相关产品推荐
相关产品推荐

