Friday, November 12, 2010

JSP tag files and dynamic attributes

In a JSP tag file sometimes you need to test for the presence of an attribute rather than whether it's empty or not. I needed to know if the id attribute was specified even if the value was empty (""). This is because with Spring's form tags, if you pass any id at all, it uses what you passed even if it's empty, otherwise it generates its own id.

My entire tag file was more complicated than what's below, but this gives you the parts you need to know.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="frm" uri="http://www.springframework.org/tags/form"%>

<%@ tag dynamic-attributes="columnMap"%>

<c:set var="hasId" value="false" />
<c:forEach var="attr" items="${columnMap}">
    <c:if test="${attr.key eq 'id'}"><c:set var="hasId" value="true" /></c:if>
</c:forEach>

<c:if test="${hasId eq true}">
    <frm:input id="${columnMap.id}" />
</c:if>

No comments:

Post a Comment