开发者

BigDecimal evaluated as a string in Velocity, Struts2

I am using struts2 with Velocity 1.5 and Velocity Tools 1.3. In my template I want to do a loop like:

#set ($count = 开发者_开发技巧${item.qty})
#foreach($i in [1..$count])
    ${item.price}
     ...........
#end

${item.qty} is a BigDecimal but it seems like its passed to Velocity as a String maybe. Since this loop does not work. Replacing to $count = 5 works fine, and printing ${item.qty} gives me a result of 5. Velocity 1.5 and Tools 1.3 is the highest version Struts2 will support. Ideas? Workarounds? Thanks


I think you need to cast/convert it to an integer for your loop to work.

#set ($count = $item.getQty().intValue())


perhaps you need to implement your own iterator - it will just store the start and end of the list of bigDecimals, and return the current one. This way, you can have an unlimited sized list of numbers (i assume that is what you wanted because you are using BigDecimals. Otherwise, just use an int or a long):

#set ($countIterator = ${item.qtyIterator})
#foreach($i in $countIterator)
    ${i}
     ....use $i as a string...
#end

and

public class QuantityIterator implement Iterator<BigDecimal> {
   QuantityIterator(BigDecimal start, BigDecimal end) { this.start = start;this.end=end;}
   //..implement the iterator methods like hasNext() etc
   public hasNext() {return this.current.compareTo(this.end) < 0;} //current <= end
   public BigDecimal next() {
      if (!hasNext()) {
         throw new NoSuchElementException();
      }
      this.current = this.current.add(BigDecimal.ONE);
      return this.current;
   }
   public void remove(){throw new UnsupportedException();}
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜