2013-06-28 22 views
17

我正在使用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"> 

有誰知道隱藏標籤的目的是什麼?如果隱藏的輸入標籤被刪除會發生什麼?

謝謝!

回答

20

隱藏的輸入標記用於指示最初是表單的一部分的字段。當表單被提交時,複選框輸入字段只有在具有值(即「檢查」)時才被髮送。如果沒有選擇,則不發送任何內容。下劃線前綴隱藏字段用於指示它是表單的一部分,但應默認爲「未檢查/錯誤」。

您可以通過創建一個帶有複選框字段的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) 
*/ 
+0

非常感謝您的輸入! 「如果沒有選擇,則不會發送任何內容。」?由瀏覽器發送?你的意思是它是HTML規範的一部分嗎? – curious1

+2

是的,它是HTML規範的一部分。表單提交後,未經檢查的複選框值不會被瀏覽器發送到服務器。一般的解決方法是在服務器端設置一個隱藏字段(比如Spring的前綴「_」或後綴「.hidden」),並檢查是否存在將值設置爲「unchecked」或「false」。有關詳細信息,請參閱W3C表單規範的第3步:http://www.w3.org/TR/html5/forms.html#constructing-form-data-set – sehrope

+0

還有一個問題:將隱藏的輸入元素表格上的任何位置? – curious1

相關問題