tokhi
tokhi

Reputation: 21618

for loop to jstl forEach

How to convert below for loop to a jstl foreach:

for(int i = 0 ; i<=21; i+=3){
  // print foo
}

This is what I have so far:

<c:forEach varStatus="loop" begin="0" end="21">
  // display foo
</c:forEach>

Upvotes: 6

Views: 27622

Answers (4)

Dakos
Dakos

Reputation: 1

Also if you want to use the value itself, you can use the 'current' attribute.

<c:forEach begin="0" end="2" varStatus="position">
   ${position.current}
</c:forEach>

this will give:

0 1 2

this is usefull when you are working with arrays which are zero-based.

Upvotes: -2

Abin Oommen George
Abin Oommen George

Reputation: 11

`<c:forEach
items="<object>"
begin="<int>"
end="<int>"
step="<int>"
var="<string>"
varStatus="<string>">
</c:forEach>`

items -- Collection of items to iterate in the loop

begin -- Begin index of the iteration. Iteration begins at the value mentioned in this attribute value. (if items specified) First item has index of 0.In your case begin="0"

end -- End index of the iteration. Iteration stops at the value mentioned in this attribute value (inclusive). (if items specified).In your case begin="49".

step -- Step value for the iteration specified in this attribute.In your case step="3".

var -- Name of the scoped variable which holds the current item in the iteration. This variable’s type depends on the items in the iteration and has nested visibility.

varStatus -- Name of the scoped variable which holds the loop status of the current iteration. This variable is of type javax.servlet.jsp.jstl.core.LoopTagStatus and has nested visibility.

to increment by 3 --> step="3"

end loop on 49 --> end="49"

link

Upvotes: -1

SpringLearner
SpringLearner

Reputation: 13844

you can use jstl step attribute

<c:forEach varStatus="loop" begin="0" end="21" step="3">
  // display foo
</c:forEach>

JSTL tutorial

Upvotes: 3

user987339
user987339

Reputation: 10707

Acoording to jstl you should try:

<c:forEach begin="0" end="21" step="3" varStatus="loop">
    <c:out value="${loop.count}"/>
</c:forEach>

Upvotes: 11

Related Questions