Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated values within JSP for-each tag

Tags:

java

jsp

jstl

I am trying to get a JSTL <c:forEach> tag to work so that it would print a list of names as follows:

Best, Milo, Kane

My code is as follows:

<c:forEach items="${persons}" var="person">
    ${person.name}, 
</c:forEach>

However, on the last person/name, a comma is inserted at the end, e.g.

Best, Milo, Kane,

How can I avoid the last comma in the loop?

like image 456
blackpanther Avatar asked Sep 13 '13 10:09

blackpanther


People also ask

How Split Comma Separated Values in JSP?

In this example, we first split a comma separate String using forTokens tag by specifying delims=";". When we iterate over tokens, var represent current token. In the second example, we have specified multiple delimiter in delims attribute, delims="|," to split String by pipe(|) character and comma (,) character.

How do you handle Comma Separated Values in Java?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

Which tag in JSTL is used to iterate over a string by splitting with supplied delimiters?

The <c:forTokens> tag is used to iterate over a string value separate by a delimiter.


1 Answers

You could use LoopTagStatus#isLast

<c:forEach items="${persons}" var="person" varStatus="loop">
    ${person.name}
   <c:if test="${!loop.last}">,</c:if>
</c:forEach>

A simpler solution is to use a conditional operator within EL instead of the if tag

${!loop.last ? ',' : ''}
like image 155
Reimeus Avatar answered Sep 22 '22 07:09

Reimeus