Java 如何在 JSTL/JSP 中的循环中连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2542436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:05:03  来源:igfitidea点击:

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

javastringjsploopsconcatenation

提问by qodeninja

<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...

我想连接 currentItem.myVar 的值并在循环结束时输出它,问题是我不知道如何做到这一点......

(Preferably not using Java)

(最好不要使用Java)

采纳答案by harto

Perhaps this will work?

也许这会奏效?

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

回答by Kapil D

define a String variable using the JSP tags

使用 JSP 标签定义一个 String 变量

<%!
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>

回答by Ben J

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

您使用的是 JSTL 2.0 对吗?你不需要把<c:out/>所有的变量都放在一边。你有没有尝试过这样的事情?

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

Edit: Beaten by the above

编辑:被上述击败

回答by Niklas Peter

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

是 JSTL 的join(),您搜索的是什么?

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