Representation of a simple for loop in JSTL/EL

2019-02-04 09:39发布

问题:

I need to represent the following for loop (in Java context) in JSTL/EL.

for (int i = 6; i <= 15; i++) {
  System.out.print(i+"\t");
}

It would display the following output.

6      7      8       9       10       11       12       13       14       15

How can I do the same in JSTL/EL? I have no precise idea about it. I'm just trying the following.

<c:forEach begin="6" end="15" varStatus="loop">
    <c:out value="${loop.count}"/>
</c:forEach>

and it would obviously display the following output.

1 2 3 4 5 6 7 8 9 10 

It's not that I want. I need to display numbers between 6 and 15 (i.e between the specified range). I need to put such a concept to implement paging in my web application. Can I do this using EL?


\t in this statement System.out.print(i+"\t"); is not significant.

回答1:

The following should work:

<c:forEach begin="6" end="15" var="val">
    <c:out value="${val}"/>
</c:forEach>

Or the following:

<c:forEach begin="6" end="15" varStatus="loop">
    <c:out value="${loop.current}"/>
</c:forEach>

Or the following:

<c:forEach begin="6" end="15" varStatus="loop">
    <c:out value="${loop.index}"/>
</c:forEach>


回答2:

I have just come across the following solution.

<c:forEach begin="6" end="15" var="i">
    <c:out value="${i}"/>
</c:forEach>

I have removed the varStatus="loop" attribute and added the var="i" attribute. It produces the following output.

6 7 8 9 10 11 12 13 14 15 

Exactly as I wanted. The idea came from here.