4

I want to add the attributes disabled, required, and autofocus to Java Spring Forms 3.1. Thanks to some questions I found out how, but I can't get it to work for boolean attributes.

We have a form utility lib that wraps Spring Form so that we can add labels and other things.

Desired JSP:

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

Desired output HTML:

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

This works in our formUtil as JSP:include but doesn't use Spring:

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

This doesn't work in our formUtil Tag but uses Spring:

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

Question: How do I get the desired output with the desired input? I'd like to keep databinding etc in Spring so I don't want to role my own form fields.

Note: Boolean attributes in HTML5 don't support boolean values so I can't have autofocus=true. It has to be just autofocus or autofocus="autofocus".

4

1 回答 1

2

As far as I know you can't place a core tag inside a spring tag as you were trying

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

it is possible to insert jstl expressions in the value of a spring tag attribute, but they won't help you as html5 only checks if autofocus is present.

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

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

but you could do something like:

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

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

which is really verbose and difficult to mantain, especially if you have several attributes you want to add.

Another crappy workaround could be set a data-xxx attribute to mark the tags with autofocus, and with javascript modify the html by adding the attribute autofocus where data-autofocus="true":

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

And the more elegant way of doing it (I can think of now) is to extend that tag with the attributes you want to add as it is explained here: https://stackoverflow.com/a/9891714/249699

于 2013-04-09T17:03:14.243 回答