在JSP中单独访问ArrayList中的值

时间:2017-03-08 04:29:07

标签: java jsp servlets

在我的servlet中,我有以下内容。所有四个都是ArrayList<>,每个都有5个值。

    request.setAttribute("interestEarnList", interestEarnList);
    request.setAttribute("numYear", numYear);
    request.setAttribute("endBalanceList", endBalanceList);
    request.setAttribute("startBalanceList", startBalanceList);

我希望以以下形式在jsp文件中显示它们:

Year Number: ${numYear}, 
Beginning Balance of this year is: ${startBalanceList},
Ending Balance of this year is: ${endBalanceList},
Total interest earned this year: ${interestEarnList},

根据numYear arrayList的大小循环。

我试过forEach但不幸的是它会显示所有numYear值, 然后是所有startBalanceList值,依此类推。

1 个答案:

答案 0 :(得分:2)

这是一个演示。

<%@ page import="java.util.*" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%
    request.setAttribute("interestEarnList", Arrays.asList(11,22,33,44,55));
    request.setAttribute("numYear", Arrays.asList(1,2,3,4,5));
    request.setAttribute("endBalanceList", Arrays.asList(122,244,366,488,610));
    request.setAttribute("startBalanceList", Arrays.asList(111,222,333,444,555));
%>
    <c:forEach var="year" items="${numYear}" varStatus="status">
        Year Number: ${year}, <br/>
        Beginning Balance of this year is: ${startBalanceList[status.index]},<br/>
        Ending Balance of this year is: ${endBalanceList[status.index]},<br/>
        Total interest earned this year: ${interestEarnList[status.index]}<br/>
    </c:forEach>

使用该伪数据,输出为

Year Number: 1, 
Beginning Balance of this year is: 111,
Ending Balance of this year is: 122,
Total interest earned this year: 11
Year Number: 2, 
Beginning Balance of this year is: 222,
Ending Balance of this year is: 244,
Total interest earned this year: 22
Year Number: 3, 
Beginning Balance of this year is: 333,
Ending Balance of this year is: 366,
Total interest earned this year: 33
Year Number: 4, 
Beginning Balance of this year is: 444,
Ending Balance of this year is: 488,
Total interest earned this year: 44
Year Number: 5, 
Beginning Balance of this year is: 555,
Ending Balance of this year is: 610,
Total interest earned this year: 55