qodeninja
qodeninja

Reputation: 11266

How can I concatenate a string within a loop in JSTL/JSP?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="<c:out var="myVar" />" />
</c:forEach>

I want to concatenate the values of currentItem.myVar and output it at the end of the loop, problem is I can't figure out how to do this...

(Preferably not using Java)

Upvotes: 37

Views: 113115

Answers (4)

Ben J
Ben J

Reputation: 5871

You're using JSTL 2.0 right? You don't need to put <c:out/> around all variables. Have you tried something like this?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>

Edit: Beaten by the above

Upvotes: 17

Niklas Peter
Niklas Peter

Reputation: 1856

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Upvotes: 4

Kapil D
Kapil D

Reputation: 2660

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

Upvotes: -6

harto
harto

Reputation: 90483

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

Upvotes: 55

Related Questions