Search code examples
javalistjstljsp-tags

Jstl removing appended symbol


I have to display a list from the database column titled "Region" .....for every item in that list, if, it contains a child value(Division), it must show something like this,

1 NorthEast Division1 | Division2

2 Midwest Division1 | Division2 | Division3

3 South Division1 ....etc

this is what I've done so far, I've put both Regions and Divisions in separate lists and called by looping it inside the <c:foreach> as shown below,

<c:forEach var="DivisionList" items="${RegionSection.DivisionList}" varStatus="vs">
<c:if test="${DivisionList.divisionID== id}" >  
${DivisionList.title}
</c:if>
</c:forEach>

By using the above, I was able to to get and arrange the whole data without the pipe "|"....to append pipe I've tried using the "Last" condition, <c:if test="${!vs.last}"> | </c:if> but this only removes the pipe in the last item of the Division list which is not what I intended.....

Is there a workaround for this that could be implemented using Jstl or do I have to use Javascript to get it working? Any help would be greatly appreciated...

Thanks


Solution

  • You should care about the naming of your variables, because the DivisionList attribute is actually a Division, and should be named as a variable, with a lower-case d: division.

    Just use the reverse tactic: prepend a pipe before every division except the first one, and use a flag to know if the first one has already been displayed:

    <c:set var="first" value="true"/>
    <c:forEach var="division" items="${RegionSection.DivisionList}">
        <c:if test="${division.divisionID == id}">
            <c:if test="${!first}"> | </c:if><c:out value="${division.title}"/>
            <c:set var="first" value="false"/>
        </c:if>
    </c:forEach>
    

    Also, Using c:out makes sure that special HTML characters (like <, >) are properly escaped.