What value is submitted by struts checkbox tag when checkbox is unselected

prakashpoudel picture prakashpoudel · May 31, 2013 · Viewed 21.3k times · Source

I ran into this scenario.

class MyForm extends IdSelectionForm {
  private Boolean approveIt = true;
  .....
}

my JSTL form consists of

<html:checkbox property="approveIt" styleId="style1" value="true"/>

When I select checkbox and submit. In struts action I get true value set for this field. And again when I uncheck it and submit. Then also I get true value. I am wondering if it is something with default value. Should it be overridden by false when I uncheck.

Answer

JB Nizet picture JB Nizet · May 31, 2013

First of all, <html:checkbox> is a Struts tag not a JSTL tag. This tag simply generates a standard HTML input of type checkbox. And HTML checkboxes send their value as parameter value when they're checked, and don't send any parameter when they're unchecked.

So, since the default value of your form field is true:

  • if the checkbox is checked, it will be set to true by Struts
  • if the checkbox is unchecked, it won't be set to anything by Struts, and will thus keep its default value: true

The default value of the approveIt property should be false. That way, if the checkbox is unchecked, it will keep its default value (false), which is correct. And if the checkbox is checked, it will be set to true, which is also correct.