Spring MVC:如何从JSP将对象传递至Controller?
解决Spring MVC中JSP传递对应对象到Controller的问题
嘿,我来帮你搞定这个问题!你现在的代码已经在遍历listResultDisplay列表,但点击提交按钮时没法正确把对应的resultDisplay对象传到Controller,核心原因是表单里没有携带足够的对象信息让Spring MVC完成绑定。下面给你两种可行的方案,按需选择:
方案1:通过隐藏字段传递完整对象属性(适合简单对象)
如果你的ResultDisplay对象结构不复杂,可以在每个表单里添加隐藏字段,把对象的所有必要属性都传递回去,让Spring自动绑定成对象。
修改JSP代码:
<c:forEach var="resultDisplay" items="${listResultDisplay}"> <!-- 调整HTML结构:form不能直接作为table的子元素,放在<td>里更规范 --> <tr> <td>${resultDisplay.date}</td> <td>${resultDisplay.documentDisplays[0].idNumber}</td> <td>${resultDisplay.siret}</td> <td align="center"> <form:form method="POST" action="${pageContext.request.contextPath}/display" modelAttribute="resultDisplay"> <!-- 添加隐藏字段,对应ResultDisplay的每个属性 --> <form:hidden path="date"/> <form:hidden path="siret"/> <form:hidden path="documentDisplays[0].idNumber"/> <!-- 如果有其他属性,都要加上对应的hidden标签 --> <input type="submit" class="btn btn-success" value="Rechercher" name="sync" /> </form:form> </td> </tr> </c:forEach>
Controller接收代码:
确保你的ResultDisplay类有无参构造函数和所有属性的getter/setter方法,然后在Controller里直接接收:
@PostMapping("/display") public String handleSubmit(@ModelAttribute("resultDisplay") ResultDisplay resultDisplay) { // 这里就能拿到点击的那一行对应的resultDisplay对象了 // 执行你的业务逻辑 return "your-target-view"; }
方案2:传递唯一ID,Controller重新获取对象(更推荐)
如果对象结构复杂(比如包含集合、嵌套对象),或者不想暴露过多属性到前端,更安全简洁的方式是传递对象的唯一标识(比如id),然后在Controller里根据ID从数据库/服务层重新获取完整对象。
修改JSP代码:
<c:forEach var="resultDisplay" items="${listResultDisplay}"> <tr> <td>${resultDisplay.date}</td> <td>${resultDisplay.documentDisplays[0].idNumber}</td> <td>${resultDisplay.siret}</td> <td align="center"> <form method="POST" action="${pageContext.request.contextPath}/display"> <!-- 只传递唯一标识,比如id --> <input type="hidden" name="displayId" value="${resultDisplay.id}"/> <input type="submit" class="btn btn-success" value="Rechercher" name="sync" /> </form> </td> </tr> </c:forEach>
Controller接收代码:
@PostMapping("/display") public String handleSubmit(@RequestParam("displayId") Long displayId) { // 调用服务层或DAO,根据ID获取对应的ResultDisplay对象 ResultDisplay resultDisplay = yourDisplayService.getById(displayId); // 执行业务逻辑 return "your-target-view"; }
额外注意事项
- 去掉重复的
id="monSubmit":循环里生成相同的ID会违反HTML规范,建议删掉或者改成动态ID(比如id="submit-${resultDisplay.id}")。 - 确保HTML结构合法:表单不要直接放在
<table>或<tr>标签下,放在<td>里是更规范的写法,避免浏览器解析异常。
内容的提问来源于stack exchange,提问作者Mékilèkon
相关产品推荐
相关产品推荐

