0

Using this post I know that if a collection have only 1 value and that is string, then it is returned as String and not as Collection Object. My problem is that my collection can have anything ranging from Integer to BigDecimal to String returned in the collection. If I used below JSTL condition then it only catches the String type data. What about other types?

Here queryResults contains List of array of Objects : List<Object[]>. Therefore bookmark should be array of Objects: Object[]

        <c:forEach var="bookmark" items="${queryResults}" varStatus="loopStatus">
            <tr class="${loopStatus.index % 2 == 0 ? 'roweven' : 'rowodd'}">
            <c:choose>
            <c:when test="${bookmark.getClass().simpleName == 'String'}">
             <!--The collection has only 1 record and that is of type String. Can't run for loop. -->
                <td><c:out value="${bookmark}"/></td>
            </c:when>
            <c:otherwise>
                <!--The collection has more than 1 record therefore running a for loop. -->
                <c:forEach begin="0" end="${fn:length(bookmark)-1}" varStatus="loop" >
                    <td><c:out value="${bookmark[loop.count-1]}"/></td>
                </c:forEach>
            </c:otherwise>
            </c:choose>
            </tr>
        </c:forEach>
Community
  • 1
  • 1
sunny_dev
  • 765
  • 3
  • 15
  • 34

1 Answers1

0

The following should work the way that you want:

    <c:forEach var="bookmark" items="${queryResults}" varStatus="loopStatus">
        <tr class="${loopStatus.index % 2 == 0 ? 'roweven' : 'rowodd'}">
            <c:forEach var="bookmarkColumn" items="${bookmark}" >
                <td><c:out value="${bookmarkColumn}"/></td>
            </c:forEach>
        </tr>
    </c:forEach>
Steve C
  • 18,876
  • 5
  • 34
  • 37
  • You see, that is the problem. If the bookmark collection has only 1 item in it say a String, then bookmark itself behaves as String and not as collection. Thats why, I wrote extra c:when condition above; if Collection have 1 record only treat it differently, else treat it as Collection and run a for loop over it. By the way your solution gives me error: javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach> – sunny_dev Nov 19 '14 at 07:23
  • That implies that you are actually populating it with a String instead of an array – Steve C Nov 19 '14 at 07:25
  • I am using hibernate session.createSQLQuery(). If there is only 1 Object instead of array of Objects to be returned, it is actually populating that 1 Object(String or Interger etc) itself as the 1st element of the List instead of populating it as array element and then populating that array in the list. Anyway, can you help in this scenario as I don't have control over java DAO code, I have to handle it in JSP only. – sunny_dev Nov 19 '14 at 09:47