I am programming in Java and I have a list of objects I'd like to iterate in JSTL to check if other elements have some similarity with current one. And I'd like to do it in my jsp because it's just a display matter.
Let's take a dummy example and say my object has three properties : id, lastname and firstname. id would be the identifier of a family and I want to display the list in an HTML table BUT while iterating my list I want to check the rest of the list to see if other family members are present so I could regroup them in one td tag.
1 | TOTO | James 2 | FOE | Cameron 2 | FOE | Je开发者_运维知识库ssica 1 | TOTO | Pat 3 | SAMPLE | Bob
Expected result :
<table>
<tr><td>1</td><td>TOTO</td><td>James, Pat</td></tr>
<tr><td>2</td><td>FOE</td><td>Cameron, jessica</td></tr>
<tr><td>3</td><td>SAMPLE</td><td>Bob</td></tr>
</table>
Again, this is a basic example and you might be tempted to tell me to regroup my families in an other object in my Model layer but I'd rather not to do that.
Edit: I am implying a while loop because my list is ordered by id so I could easily check the next elements. But other solutions would be fine for me.
You can get hold of processed lastnames in a Map
and intercept on that.
<table>
<jsp:useBean id="processed" class="java.util.HashMap" />
<c:forEach items="${persons}" var="person">
<c:if test="${empty processed[person.lastName]}">
<c:set target="${processed}" property="${person.lastName}" value="true" />
<tr>
<td>${person.familyId}</td>
<td>${person.lastName}</td>
<td>${person.firstName}
<c:forEach items="${persons}" var="other">
<c:if test="${person.lastName == other.lastName and person.firstName != other.firstName}">
, ${other.firstName}
</c:if>
</c:forEach>
</td>
</tr>
</c:if>
</c:forEach>
</table>
I however agree that this should rather be done in the (data)model side, not in the view side.
Your bean should do the grouping, not the JSP.
精彩评论