开发者

issue of JSTL forEach iterate from arrayList

In my code, I have used ArrayList which stores the number fo开发者_JS百科rmat like '$0.00 to $1,000,000.00' in each index of array list. while iterate in JSP through <c:forEach> tag, its values are printing like

$0.00 to $1 as a first string, 000 as a second string and 000.00 as a thrid string. but it has to print like '$0.00 to $1,000,000.00'.

what will be the problem is?

Thanks in advance


You are iterating over element of array, not over array itself. Thus the element of the array "$0.00 to $1,000,000.00" is split at comma positions and you get individual elements as you have described.

Following is an example:

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
 java.util.ArrayList list = new java.util.ArrayList();
 list.add("$0.00 to $1,000,000.00");
 list.add("$1,000,000.00 to $1,000,000,000.00");
 request.setAttribute("list", list);
%>

<h1>Iterating over ArrayList</h1>
<ul>
 <c:forEach items="${list}" var="value">
  <li><c:out value="${value}"/></li>
 </c:forEach>
</ul>

<h1>Iterating over first element of ArrayList</h1>
<ul>
 <c:forEach items="${list[0]}" var="value">
  <li><c:out value="${value}"/></li>
 </c:forEach>
</ul>


I'm not sure if I got this right, but consider using the JSTL fmt tag library. Its formatNumber tag can handle currencies. Your example would then become:

<c:forEach var="item" items="list">
    <fmt:formatNumber type="currency" currencySymbol="$" value="${item}" currencyCode="USD" />
</c:forEach>


hey I had the same problem, the solution is to trim the spaces in the for:each tag.

So instead of this (notice the space before the '>' )

c:forEach items="${list}" var="value" > 

to

c:forEach items="${list}" var="value"> 

// no spaces.

This will work for sure.. Its frustrating... but that's the way it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜