我正在使用Spring,其中我的表单字段与属性字段相同,所以当我提交表单时,它直接映射到数据库字段并保存数据,它完美地工作,但是如果我想用一个表单保存多个对象,< / p>
HTML:
<form>
Payment:<br>
<input type="text" name="payment"><br>
Date:<br>
<input type="date" name="paymentDate">
</form>
POJO:
public class ProjectPayment
{
private Double payment;
private Date paymentDate;
// setters and getters
}
控制器:
@RequestMapping(value = "/addnewproject", method = RequestMethod.POST)
public @ResponseBody String SaveProject(ProjectPayment projectPayment) {
projectPaymentService.saveProjectPayment( projectPayment);
}
这很有效, 但现在在我的某些场景中,我需要动态地需要多个对象,然后如何在数据库中保存,控制器应该如何显示
例如:
现在我的表格是
<form>
Payment:<br>
<input type="text" name="payment"><br>
Date:<br>
<input type="date" name="paymentDate">
Payment:<br>
<input type="text" name="payment"><br>
Date:<br>
<input type="date" name="paymentDate">
Payment:<br>
<input type="text" name="payment"><br>
Date:<br>
<input type="date" name="paymentDate">
Payment:<br>
<input type="text" name="payment"><br>
Date:<br>
<input type="date" name="paymentDate">
</form>
现在这个表单有多个ProjectPayment类对象,但它只保存一个对象 请告诉我我的控制器应该如何,我已经这样做但它发生异常
控制器:
@RequestMapping(value = "/addnewproject", method = RequestMethod.POST)
public @ResponseBody String SaveProject(ProjectPayment[] projectPayment) {
for(ProjectPayment propay : projectPayment)
{
projectPaymentService.saveProjectPayment( propay );
}
}
答案 0 :(得分:1)
我可以理解你想要从网格/表中发布数据,但是它太模糊不清以确定哪个对象的字段映射。 例如:
- FIELD1
- FIELD2
- field3 ==&gt;映射到索引1或2的对象?
- filed1
所以你认为field3应该映射到数组index = 1或index = 2? 因此,我建议您逐一提交以解决此问题。
答案 1 :(得分:0)
解决此问题的简单方法是创建一个ViewModel。
e.g。
public class ProjectPaymentViewModel
{
private List<ProjectPayment> listProjectPayment;
// setters and getters
}
在网页和控制器上使用此视图模型
<form>
Payment:<br>
<input type="text" name="listProjectPayment[0].payment"><br>
Date:<br>
<input type="date" name="listProjectPayment[0].paymentDate">
Payment:<br>
<input type="text" name="listProjectPayment[1].payment"><br>
Date:<br>
<input type="date" name="listProjectPayment[1].paymentDate">
Payment:<br>
</form>
在控制器上
@RequestMapping(value = "/addnewproject", method = RequestMethod.POST)
public @ResponseBody String SaveProject(ProjectPaymentViewModel projectPaymentViewModel) {
for(ProjectPayment propay : projectPaymentViewModel.getListProjectPayment())
{
projectPaymentService.saveProjectPayment( propay );
}
}