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

徘徊边缘 提交于 2020-01-01 11:37:51

问题


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.


回答1:


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.




回答2:


I was having the same problem. The problem persisted even after the boolean variable was initialized to false.

The problem was my scope was session.

Upon changing the scope to request everything works as expected.




回答3:


The value attribute contains the value used by the tag and has nothing with checkbox state, if it's checked or unchecked.

On submit, only checked checkboxes are passed. Then Struts catches them and set corresponding by name bean properties.

If you per-initialize the value inline or in constructor then only checked checkboxes will be updated by setting a bean property value. You cannot update the unchecked state.

Therefore don't set any value before the form is populated. If the value is not set then Struts treats that value as false and removes checked from the tag. This is equivalent by setting the value to false explicitly.

The opposite behavior with the value true but checkbox has not a state for the other values like null rather than true or false that corresponds to the state of checkbox checked or unchecked (without checked attribute).



来源:https://stackoverflow.com/questions/16866351/what-value-is-submitted-by-struts-checkbox-tag-when-checkbox-is-unselected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!