Spring MVC and form binding : how to remove an item from a List?

Explanation

When you load a page with <form:form modelAttribute="person" ...>, there are two cases :

  • case 1 : if person doesn't exist, it creates an empty Person
  • case 2 : if person already exists, it uses it

In all cases, when a page is loaded, there is an existing person.
When you submit a form, Spring MVC updates this existing person only with the submitted information.

So in case 1, if you submit email 1, 2, 3 and 4, Spring MVC will add 4 emails to the empty person. No problem for you in this case.

But in case 2 (for example when you edit an existing person in session), if you submit email 1 and 2, but person has already 4 emails, then Spring MVC will just replace email 1 and 2. Email 3 and 4 still exist.


A possible solution

Probably not the best one, but it should work.

Add a remove boolean to the Email class :

...
public class Email {

    ...

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

    ...

}

In the save method of your controller, remove the emails that have remove set to true.

Finally, in your JSP, add this hidden field :

<form:hidden path="emails[${status.index}].remove" />

And tell your Javascript to set the input value to true when the user clicks to delete the email.