Today I was trying to create an equivalent of displaytag. During the exercise I found out few things a didn't know about the behavior of JSP tag files.
My code was as follows:
The jsp:
I thought that it was just that I didn't understand the whole "variable" thing in tag files (which was likely), so I change my code the following way:
The table.tag file:
The jsp:
<mdisplay:table collection="${requestScope.mycollection}">
<mdisplay:column property="id">
</mdisplay:column>
</mdisplay:table>
The table.tag file:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="collection" required="true" rtexprvalue="true"%>
<%@ variable name-given="item" scope="NESTED" declare="true" %>
<c:foreach items="${collection}" var="item">
<jsp:dobody>
</jsp:dobody>
</c:foreach>
The column.tag file:
<%@ attribute name="property" required="true" %>
${item[property]}
Result: didn't work.I thought that it was just that I didn't understand the whole "variable" thing in tag files (which was likely), so I change my code the following way:
The table.tag file:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="collection" required="true" rtexprvalue="true"%>
<%@ variable name-given="item" scope="NESTED" declare="true" %>
<c:foreach items="${collection}" var="item">
<c:set var="item" value="${a}" scope="request">
<jsp:dobody>
</jsp:dobody>
</c:set>
</c:foreach>
The column.tag file:
<%@ attribute name="property" required="true" %>
${requestScope.item[property]}
It didn't work either, throwing an exception stating " cannot find property id in class String"... WTH?
It ends up that if you don't specify the type of a tag attribute, it is assumed to be "String". By stating that "collection" is in fact a java.util.Collection, everything worked fine:
The table.tag file:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="collection" required="true" rtexprvalue="true" type="java.util.Collection"%>
<%@ variable name-given="item" scope="NESTED" declare="true" %>
<c:foreach items="${collection}" var="item">
<c:set var="item" value="${a}" scope="request">
<jsp:dobody>
</jsp:dobody>
</c:set>
</c:foreach>
It would have been nice that the JSP processor had the capability to infer the type of the parameter, but things are the way they are.
Happy Coding!
Leave a comment