Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 794
qodeninja Avatar asked Mar 30 '10 02:03

qodeninja


People also ask

How do you concatenate a string in a for loop?

Python concatenate strings in for loop To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings in python.

How do you concatenate values in JSTL?

JSTL - fn:join() Function The fn:join() function concatenates all the elements of an array into a string with a specified separator.

How do I concatenate strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


2 Answers

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">   <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" /> </c:forEach> 
like image 56
harto Avatar answered Sep 21 '22 18:09

harto


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

like image 27
Ben J Avatar answered Sep 22 '22 18:09

Ben J