Java Spring Form Fields with HTML5 Boolean Attributes

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

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

Desired JSP:

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

Desired HTML output:

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

It works in our form. As a JSP: include, but not using Spring:

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

This does not 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 to get the desired result with the right input? I would like to keep data binding, etc. In Spring, so I don't want my own form fields to be.

Note: Boolean attributes in HTML5 do not support booleans, so I cannot have autofocus=true . It should be just autofocus or autofocus="autofocus" .

+4
source share
1 answer

As far as I know, you cannot put the main tag inside the spring tag as you tried

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

you can insert jstl expressions into the attribute value of the spring tag, but they will not help you, since html5 checks for autofocus.

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

but you can 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, especially if you have several attributes that you want to add.

Another crap workaround is to set the data-xxx attribute to tag the tags with autofocus, and use javascript to change the html by adding the autofocus attribute, where data-autofocus = "true":

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

And a more elegant way to do this (I can think now) is to expand this tag with the attributes you want to add, as explained here: fooobar.com/questions/1450703 / ...

+2
source

All Articles