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:
<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!

No TrackBacks

TrackBack URL: http://tech.soronthar.com/mt/mt-tb.cgi/49

Leave a comment

About this Entry

This page contains a single entry by Soronthar published on November 9, 2009 12:55 AM.

Comparable vs. Comparator: A response was the previous entry in this blog.

TWiki/Foswiki Facts is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.