我有这堂课:
PreApprovalRequest类有一个属性headings
,它会在控制器中自动填充(参见页面上控制器的代码)。
public class PreApprovalRequest {
private Long id;
private String Description;
private Collection<Headings> headings; //this property!
}
控制器:
@Controller
@SessionAttributes({"preApprovalRequest", "productRecommendations"})
public class RequestController {
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitResults(@ModelAttribute(value = "preApprovalRequest") @Valid PreApprovalRequest preApprovalRequest, BindingResult errors) {
//HERE: It looks like if I have some headings in the preApprovalRequest object already, the call of this method will not delete those, but will append to the existing list.
//save object in DB.
return "dashboard";
}
}
知道如何让Spring替换集合对象而不是添加它吗?
答案 0 :(得分:0)
我如何理解您的问题,您无法将headings
个集合替换为Headings
的新集合。你不能用以下方式做到吗?
preApprovalRequest.setHeadings(new ArrayList<Headings>());
preApprovalRequest.getHeadings().add(heading1);
答案 1 :(得分:0)
即使是您第一次提交表单,是否会发生这种情况?如果没有,请在完成控制器中的所有操作后尝试清理缓存。
在方法中添加SessionStatus并调用“setComplete()”来清除属性。因此,第二次启动进程时,缓存将为空,您将不得不使用新的preApprovalRequest
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitResults(@ModelAttribute(value = "preApprovalRequest") @Valid PreApprovalRequest preApprovalRequest, BindingResult errors, SessionStatus status) {
/HERE: It looks like if I have some headings in the preApprovalRequest object already, the call of this method will not delete those, but will append to the existing list.
//save object in DB.
status.setComplete();
return "dashboard";
}
答案 2 :(得分:0)
如果您正在寻找的是动态缩小/扩展类型的List,那么集合必须是lazy.Apache commons集合提供了一个Lazy List类来执行此操作。您可以从{{3}获取apache commons集合}
因此您的控制器模型可以重写为:
public class PreApprovalRequest {
private Long id;
private String Description;
private List headings;
public PreApprovalRequest()
{
headings=LazyList.decorate(
new ArrayList(),
FactoryUtils.instantiateFactory(Header.class));
}
}
将数据绑定到列表背后的想法是,在html元素名称属性中跟踪列表项索引:
<c:forEach item="${modelAttr.list}" varStatus="listItem">
<form:input type="text" path="list[${listItem.index}]" />
</c:forEach>