Spring form checkbox标签:为什么生成隐藏元素?

cur*_*us1 19 spring-mvc

我正在使用Spring MVC作为Web应用程序.在表格上,我有

<form:checkbox path="agreeTerms" id="agreeTerms"/>
Run Code Online (Sandbox Code Playgroud)

呈现页面时,将生成以下HTML

<input id="agreeTerms" type="checkbox" value="true" name="agreeTerms">
<input type="hidden" value="on" name="_agreeTerms">
Run Code Online (Sandbox Code Playgroud)

有谁知道隐藏标签的目的?如果隐藏的输入标记被删除会发生什么?

谢谢!

seh*_*ope 22

隐藏的输入标记用于指示最初属于表单的字段.提交表单时,仅当复选框输入字段具有值(即"已检查")时才会发送该字段.如果未选中,则不发送任何内容.下划线前缀隐藏字段用于表示它是表单的一部分,但应默认为"un-checked/false".

您可以通过创建带有复选框字段的HTML表单并在未选中字段的情况下提交它来测试此问题.

另外,要了解它是如何完成的,请查看WebDataBinder的源代码:

/**
* Check the given property values for field markers,
* i.e. for fields that start with the field marker prefix.
* <p>The existence of a field marker indicates that the specified
* field existed in the form. If the property values do not contain
* a corresponding field value, the field will be considered as empty
* and will be reset appropriately.
* @param mpvs the property values to be bound (can be modified)
* @see #getFieldMarkerPrefix
* @see #getEmptyValue(String, Class)
*/
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是HTML规范的一部分.表单提交时,浏览器不会向服务器发送未选中的复选框值.一般的解决方法是有一个隐藏字段(例如像Spring一样带有"_"前缀或后缀为".hidden")并检查它是否存在,以便在服务器端将值设置为"unchecked"或"false".有关详细信息,请参阅W3C表单规范的步骤3:http://www.w3.org/TR/html5/forms.html#constructing-form-data-set (2认同)