Spring : Binding (multiple) checkboxes
This page last changed on Jun 19, 2006 by Kees de Kooter
Binding a single checkbox to a form bean
We are using xml compliant JSP so it is a bit verbose . The trick is to add a hidden input tag prefixed with an underscore. Since the browser does not return anything for an unchecked chekbox this way Spring can determine that a checkbox was set to false.
<spring:bind path="acceptDeliveryConditions">
<input type="hidden" name="_${status.expression}"/>
<c:choose>
<c:when test="${status.value == true}">
<input type="checkbox" name="${status.expression}"
checked="checked"/>
</c:when>
<c:otherwise>
<input type="checkbox" name="${status.expression}"/>
</c:otherwise>
</c:choose>
</spring:bind>
Binding a multiple checkboxes to an array property of a form bean
The form contains a List
named types
. These are pojos that have a checked
attribute. Spring sets this property after the form is submitted. In the form processing code these checked properties can be read and acted on.
<c:forEach items="${form.types}" var="type" varStatus="loopStatus">
<spring:bind path="types[${loopStatus.index - 1}].checked">
${status.errorCode}
<input type="hidden" name="_${status.expression}"/>
<c:choose>
<c:when test="${status.value}">
<input type="checkbox" name="${status.expression}"
value="true" checked="checked"/>
</c:when>
<c:otherwise>
<input type="checkbox" name="${status.expression}"
value="true"/>
</c:otherwise>
</c:choose>
</spring:bind>
</c:forEach>