0

我有这堂课:

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 替换集合对象而不是添加到它吗?

4

3 回答 3

0

我如何理解你的问题是,你不能替换你的headings收藏来拥有一个新的Headings. 你不能通过以下方式做到这一点吗?

preApprovalRequest.setHeadings(new ArrayList<Headings>());
preApprovalRequest.getHeadings().add(heading1);
于 2013-01-25T05:01:34.663 回答
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";
}
于 2013-01-25T10:21:53.387 回答
0

如果您正在寻找的是动态收缩/扩展类型的列表,那么集合必须是惰性的。Apache commons 集合提供了一个惰性列表类来执行此操作。您可以从以下位置获取 apache commons 集合:http://commons.apache .org/collections/

所以你的控制器模型可以重写为:

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>
于 2013-01-25T11:19:09.543 回答