java – Spring MVC和表单绑定:如何从List中删除项目?

前端之家收集整理的这篇文章主要介绍了java – Spring MVC和表单绑定:如何从List中删除项目?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个Person模型属性,其中包含电子邮件列表.
我创建了一些Javascript代码,用于删除html电子邮件列表中的元素.这是纯Javascript客户端代码,没有AJAX调用.

提交后,我不明白为什么我在相应的@Controller方法获取所有电子邮件,甚至是在html中删除的电子邮件.

有人可以解释一下吗?

JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">Meta>
    

控制器:

@Controller
@SessionAttributes(types={Person.class},value={"person"})
public class PersonController {

    private final static String PERSON_VIEW_NAME = "person-form";

    private ResumeManager resumeManager;

    @Autowired()
    public PersonController(ResumeManager resume) {
        this.resumeManager = resume;
    }

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
    }

    @RequestMapping(value="/person/edit/save")
    public String save(@modelattribute(value="person") Person p,BindingResult result,SessionStatus status) {
        new PersonValidator().validate(p,result);
        Collections.sort(p.getEmails()); //this collection still contains client-side dropped objects

        this.resumeManager.savePerson(p);

        return PERSON_VIEW_NAME;
    }
}
最佳答案
说明

当您使用< form:form modelAttribute =“person”...>加载页面时,有两种情况:

>案例1:如果人不存在,则会创建一个空人
>案例2:如果人已经存在,则使用它

在所有情况下,当加载页面时,存在现有人.
提交表单时,Spring MVC仅使用提交的信息更新此现有人员.

因此,在案例1中,如果您提交电子邮件1,2,3和4,Spring MVC将向空人添加4封电子邮件.在这种情况下你没问题.

但是在案例2中(例如,当您在会话中编辑现有人员时),如果您提交电子邮件1和2,但是人员已经有4封电子邮件,则Spring MVC将仅替换电子邮件1和2.电子邮件3和4仍然存在.

可能的解决方

可能不是最好的,但它应该工作.

在Email类中添加一个删除布尔值:

...
public class Email {

    ...

    private boolean remove; // Set this flag to true to indicate that 
                            // you want to remove the person.

    ...

}

在控制器的save方法中,删除已将remove设置为true的电子邮件.

最后,在JSP中添加以下隐藏字段:

并告诉您的Javascript在用户单击以删除电子邮件时将输入值设置为true.

原文链接:https://www.f2er.com/spring/432741.html

猜你在找的Spring相关文章