Java 将集合绑定到表单-为什么不起作用?
有人能帮我找出为什么我在SpringMVC中将集合绑定到表单的尝试不起作用吗 下面是我的对象的外观-Java 将集合绑定到表单-为什么不起作用?,java,spring,spring-mvc,Java,Spring,Spring Mvc,有人能帮我找出为什么我在SpringMVC中将集合绑定到表单的尝试不起作用吗 下面是我的对象的外观- public class TestObj { private Integer testNumber; private String home; private String destination; } 这是我的表单对象,它包含上述对象的列表- public class TestForm { private List<TestObj> testList;
public class TestObj {
private Integer testNumber;
private String home;
private String destination;
}
这是我的表单对象,它包含上述对象的列表-
public class TestForm {
private List<TestObj> testList;
//contains getter and setter for testList
}
在我的控制器中,我实现了formBackingObject方法-
public class MyController extends SimpleFormController {
public MyController() {
setCommandClass(TestForm.class);
setCommandName("testForm");
}
protected Object formBackingObject(HttpServletRequest request) throws Exception {
if (isFormSubmission(request)) {
testForm = (TestForm) super.formBackingObject(request);
//THIS ALWAYS RETURNS NULL ON FORM SUBMISSION
List<TestObj> testList = testForm.getTestList();
} else {
//load initial data using hibernate. TestObj is hibernate domain object.
List<TestObj> testList = myService.findTestList();
testForm = new TestForm(testList);
}
return testForm;
}
这是我的JSP代码片段-
<form:form commandName="testForm" method="post">
<c:forEach items="${testForm.testList}" var="testvar" varStatus="testRow">
<tr>
<td>
<form:hidden path="testList[${testRow.index}].home" />
<c:out value="${testvar.home}" />
</td>
<td>
<form:input path="testList[${testRow.index}].destination" />
</td>
</tr>
</c:forEach>
<tr><td><input type="submit"></td></tr>
</form:form>
当我第一次加载数据时,数据在表单上显示良好,当我按下submit按钮时,控件转到formBackingObject方法,isFormSubmission返回true。但是,当我使用super.formBackingObjectrequest获取命令对象时,它返回testList值为null的表单对象。我无法理解为什么这个简单的案例不起作用
我将非常感谢您能为我提供帮助。您正在使用Spring 3吗?如果是这样的话,你应该看看
关于列表处理和对象绑定,请查看。尝试使用以下代码。也许这能解决你的问题
private List<TestObj> operationParameterses = LazyList.decorate(new ArrayList<TestObj>(), FactoryUtils.instantiateFactory(TestObj.class));
它不会返回所有空列表
希望这对你有帮助
干杯。我想我对formBackingObject方法的理解一定是错误的。我从实现中删除了该方法,使用referenceData进行初始表单加载,并在提交时使用onSubmit进行处理。这可以很好地工作,并且确实可以按预期返回表单中的集合
谢谢大家的帮助。谢谢你的回复。我刚刚接管了一个使用Spring2.0的应用程序,因此还不能使用Spring3.0+的任何功能。我还查看了您发布的关于绑定的第二个链接,并从其中提到的另一个链接中找到了AutoPopulationGlist的用法。然而,这仍然没有帮助,因为我得到了所有空值的列表。我的经验仅限于Spring3。我会做一点挖掘,看看我是否能进一步提供帮助,但为了你的缘故,希望其他人能尽快回复!:您还需要commons collection library来实现这一点。谢谢您的建议。我要试试看。您是否建议将其放在我的代码中的TestForm中,以使用上述代码初始化testList?这仍然不起作用。我不明白为什么表单上的项目没有被映射。表单TestForm不会返回null,但在提交时,其中的列表始终为null。我怀疑提交时的setter没有将JSP中的元素设置到表单中。我已经想不出它为什么不这么做了。