【问题标题】:BigDecimal evaluated as a string in Velocity, Struts2BigDecimal 在 Velocity、Struts2 中被评估为字符串
【发布时间】:2009-10-19 21:53:17
【问题描述】:

我正在使用带有 Velocity 1.5 和 Velocity Tools 1.3 的 struts2。在我的模板中,我想做一个像这样的循环:

#set ($count = ${item.qty})
#foreach($i in [1..$count])
    ${item.price}
     ...........
#end

${item.qty} 是一个 BigDecimal,但它似乎作为一个字符串传递给 Velocity。由于此循环不起作用。替换为 $count = 5 可以正常工作,打印 ${item.qty} 给我的结果是 5。Velocity 1.5 和 Tools 1.3 是 Struts2 将支持的最高版本。想法?解决方法?谢谢

【问题讨论】:

  • 在 bean 中将 qty 更改为 int 是否有效?

标签: java struts2 velocity


【解决方案1】:

我认为您需要将其转换/转换为整数才能使循环正常工作。

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

【讨论】:

  • 我没有意识到 Velocity 可以做到这一点。谢谢!
  • 类似于 intValue() 我们有什么东西可以将字符串转换为 BigDecimal 以免丢失精度吗?
  • new BigDecimal(stringValue)@SyedAmmar
【解决方案2】:

也许您需要实现自己的迭代器 - 它只会存储 bigDecimal 列表的开头和结尾,并返回当前的。这样,您可以获得无限大小的数字列表(我假设这是您想要的,因为您使用的是 BigDecimals。否则,只需使用 int 或 long):

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

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();}
}

【讨论】:

  • 我不认为他真的需要一个迭代次数超过整数的循环。该模板需要很长时间才能呈现并产生巨大的输出。
猜你喜欢
  • 2016-08-29
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多