How to simulate a group-by in JSTL view layer by keeping track of previous & current values while looping over a List?
First I retrieve the Note
objects in the service layer:
List<Note> notes = this.getNotes();
Then I pass List
of Notes
to the view layer and set the same initial value for prevNote
and currNote
to the first element of the List
:
<c:forEach items="${notes}" var="note" begin="0" end="1" step="1">
<c:set var="prevNote">${note}</c:set>
<c:set var="currNote">${note}</c:set>
</c:forEach>
开发者_运维知识库
Then I iterate over the List
and set prevNote
to currNote
and currNote
to the current note item (note
) from the loop:
<c:forEach items="${notes}" var="note">
<c:set var="prevNote">${currNote}</c:set>
<c:set var="currNote">${note}</c:set>
prev:<c:out value="${prevNote.userCode}"/>
curr:<c:out value="${currNote.userCode}"/>
</c:forEach>
But when I run this, I get this error message:
Unable to find a value for "note" in object of
class "java.lang.String" using operator ".
What I want to do here is check whether prevNote
and currNote
contain the same userCode
value - if they do I want to skip the current element in the List
and display the next Note
that has a different userCode
(sort of simulating a group-by
operation).
Any hints on how to do this and why I'm getting this error message?
Setting a value in the body of c:set
will essentially convert it to String
using toString()
method of the object. The exception is also hinting that you aren't working on a fullworthy Note
instance, but on a String
one.
Use the value
attribute instead.
<c:set var="prevNote" value="${note}" />
<c:set var="currNote" value="${note}" />
As to your functional requirement:
What I want to do here is check whether prevNote and currNote contain the same userCode value - if they do I want to skip the current element in the List and display the next Note that has a different userCode (sort of simulating a group-by operation).
Just storing the current note at end of the loop is sufficient. E.g.
<c:forEach items="${notes}" var="note">
<c:if test="${empty prevNote or note.userCode != prevNote.userCode}">
<c:out value="${note.userCode}" />
</c:if>
<c:set var="prevNote" value="${note}" />
</c:forEach>
精彩评论