tags:

views:

103

answers:

2

I have a page which I'm converting from Velocity to JSP. I have some complex expressions which I can't figure out how to convert to JSTL el language.

#set ($col = 0)

#foreach ($hour in $form.bean.grid.hours)
  $hour.cells.get($col).hourOfDay
  #set ($col = $col + 1)
#end

Hour is an object which contains a cell which contains a list. I need to get each element through a numeric index.

Any ideas?

A: 

Something like:

<c:set var="col" value="0"/>

<c:forEach items="${form.bean.grid.hours}" var="hour">
   ${hour.cells[col].hourOfDay}
   <c:set var="col" value="${col + 1}"/>
</c:forEach>

This will only work if hour.cells is a Map, so that the cells.get($col) expression in the original is calling get() on that Map. If it's an arbitrary method call, then it won't work, since JSP EL can only handle bean properties or collections.

As @EliteGentleman points out, you can use the varStatus on the forEach loop to remove the need for a separate loop counter, which you should do. My fragment was a more literal translation.

skaffman
Ahh, the light-bulb went ON. Thanks. I see now how EL works differently than velocity.
Dan Howard
+1  A: 

Basically, you're displaying hours of day. Using JSTL,

<c:forEach items="${form.bean.grid.hours}" var="hour" varStatus="index">
   ${hour.cells[index.count - 1].hourOfDay}
</c:forEach>

The count in index.count starts counting from 1 to N (so negate it by 1).

The Elite Gentleman
Thanks! I get it now. :)
Dan Howard
Rather use `LoopTagStatus#getIndex()`, i.e. `index.index` in the given example. It's 0-based, no need to substract it with 1. Javadoc here: http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html
BalusC
To avoid confusion, I would declare `varStatus` as `loop`. I.e. `<c:forEach ... varStatus="loop">${foo[loop.index]}</c:forEach>`. Much more self-explaining.
BalusC
Thanks BalusC, obviously you got time in your hands giving advice to every java problems on SO. :-D
The Elite Gentleman