MathJax

SyntaxHighlighter

Highlight

Custom CSS

Wednesday, January 24, 2007

SpringMVC and HTML Checkboxes

If a checkbox appears on an HTML form, but is not checked, the field will not be submitted by the browser at all. This means that SpringMVC may sometimes fail to bind a changed value. Consider the scenario:

  1. User checks a checkbox and submits.
  2. User is presented with the form again, due to validation errors.
  3. User corrects errors, but changes mind about checkbox selection and unchecks it.
  4. User resubmits form, but checkbox field is not sent, so Spring doesn't bind a value to it.
  5. User's original selection (checked) remains in the command object.

Here's the workaround from Expert Spring MVC and Web Flow:

<form ...>                                      
  <spring:bind path="command.acceptTermsAndConditions">
    <input type="checkbox" name="${status.expression}"
        value="true" ${status.value ? 'checked' : ''}/>
      I agree to the terms and conditions.
    <input type="hidden" name="_${status.expression}"/>
  </spring:bind>
</form>