2012-12-06 42 views
4

我想將屬性disabled,requiredautofocus添加到Java Spring Forms 3.1。由於somequestions我發現怎麼樣,但我不能讓它爲boolean attributes工作。具有HTML5布爾屬性的Java Spring窗體字段

我們有一個表格工具LIB一個包裝Spring表單,這樣我們可以添加標籤和其他東西。

期望中的JSP:

<formUtil:formInputBox ... autofocus="true" /> 

所需的輸出HTML:

<label>...<input type="text" ... autofocus /></label> 

這工作我們formUtil作爲JSP:包括,但不使用Spring:

<input type="text" ... <c:if test="${param.autofocus=='true'}">autofocus</c:if> /> 

這不起作用在我們formUtil標籤但使用Spring:

<form:input ... <c:if test="${autofocus==true}">autofocus</c:if> /> 
// Gives exception: `Unterminated &lt;form:input tag`. 

問: 如何獲得所需的輸出與期望的輸入?我想在Spring中保留數據綁定等,所以我不想扮演我自己的表單域。

注: 布爾在HTML5屬性,所以我不能有autofocus=true不支持布爾值。它必須只是autofocusautofocus="autofocus"

回答

2

據我知道你不能把彈簧標籤內部的核心標籤,你試圖

<form:input ... <c:if test="${autofocus==true}">autofocus</c:if> /> 

有可能在彈簧標籤屬性的值插入JSTL表達式,但他們不會幫助你,因爲html5只會檢查自動對焦是否存在。

<s:set var="autofocusVal" value=""/> 
<c:if test="${autofocus}"> 
    <s:set var="autofocusVal" value="autofocus"/> 
</c:if> 

<form:input autofocus="${autofocusVal}" /> 

,但你可以這樣做:

<c:choose> 
    <c:when test="${autofocus}"> 
     <form:input autofocus="autofocus" /> 
    </c:when> 

    <c:otherwise> 
     <form:input /> 
    </c:otherwise> 
</c:choose> 

這是非常冗長,不易十個分量,特別是如果你有你想要添加幾個屬性。

另一個糟糕的解決辦法可以設置一個數據XXX屬性標記,自動對焦的標籤,並用JavaScript通過添加屬性自動對焦修改HTML,其中數據自動對焦=「真」:

<form:input data-autofocus="${autofocus}" /> 

而且這樣做(我現在能想到的)的更優雅的方式是延長該標籤與您要添加的屬性,因爲它是在這裏解釋:https://stackoverflow.com/a/9891714/249699