Spring Form复选框标签:为什么生成隐藏元素?


问题内容

我正在将Spring MVC用于Web应用程序。在表格上,我有

<form:checkbox path="agreeTerms" id="agreeTerms"/>

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

<input id="agreeTerms" type="checkbox" value="true" name="agreeTerms">
<input type="hidden" value="on" name="_agreeTerms">

有谁知道隐藏标签的用途?如果删除了隐藏的输入标签,将会发生什么?

谢谢!


问题答案:

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

您可以通过创建带有复选框字段的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)
*/