带有HTML5布尔属性的Java Spring Form字段

时间:2012-12-06 15:47:31

标签: java forms html5 spring

我想将属性disabledrequiredautofocus添加到Java Spring Forms 3.1。感谢some questions我发现了如何,但我无法让它为boolean attributes工作。

我们有一个表单实用程序库,它包装Spring Form,以便我们可以添加标签和其他东西。

所需的JSP:

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

所需的输出HTML:

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

这在我们的formUtil中用作作为JSP:include但不使用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"

1 个答案:

答案 0 :(得分:2)

据我所知,你在尝试时不能在弹簧标签内放置核心标签

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

可以在spring标签属性的值中插入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>

这是非常冗长和难以保持的,特别是如果你想要添加几个属性。

另一个糟糕的解决方法是设置data-xxx属性以使用自动对焦标记标记,并使用javascript通过添加属性autofocus修改html,其中data-autofocus =“true”:

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

更优雅的方式(我现在可以想到)是使用您要添加的属性扩展该标记,如下所述:https://stackoverflow.com/a/9891714/249699