I have the following beans:
public class CodedEntity {
private String name;
private String code;
// getters and setters
}
public class MyProduct {
@javax.validation.constraints.Size(min = 1)
private List<CodedEntity> codedEntities;
// getters and setters
}
As you see the codedEntities list must have at least one element.
In my controller I validate the size of the list like this :
@RequestMapping(value = "/**", method = RequestMethod.POST)
public String submit(@Valid final MyProduct myProduct, final BindingResult result,
final Model model) {
// ...
}
And finally my jsp :
<c:forEach items="${codedEntitiesList}" var="codedEntity" varStatus="loopStatus"
<form:checkbox path="myProduct.codedEntities[${loopStatus.index}]" value="${codedEntity.code}" cssClass="checkbox" />
</c:forEach>
The problem here is the following : when I submit the jsp without checking any checkbox, spring mvc returns a non-empty list containing “null” elements. And because of this, the validation fails.
How can I tell spring-mvc to return an empty list instead of a list full of “null” elements ? Or at least is there any way I can validate my constraint ?
I finally found a solution. I don’t know if it’s the best one, but it’s certainly a good one.
First of all, the jsp has to be modified like this :
Than you have to create a custom editor :
Of course, do not forget to bind the CodedEntityEditor to the Controller :
Finally, you have to implement the hashCode() and equals() methods in the CodedEntity object. You have to do this because the getAsText method in the CodedEntityEditor retrieves the object by its reference.
If you implement those 2 methods, it will retrieve it on a specific field (the “code” field in my case). To make it easy I suggest to use an IDE like Eclipse to generate those automatically.
Just for the example, here are the 2 methods generated by Eclipse :
Of course you can skip those 2 methods, but in this case the checkboxes won’t be checked when you’ll reload the page !