[转] Velocity,数值和日期的格式化

Velocity的数值类型,在页面显示的时候,系统会调用toString,自动将它们转换成字符串类型。
那么,在JSP页面里,怎么进行数值类型的运算呢?其实,很简单,可直接进行运算,如下:

[javascript] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #set($result=${cpsIncome}/${newUserCount})  

然后,将计算结果($result),在页面中显示。

运算结果(0.12979978058145913)默认的小数位数很长,如何保留两位小数呢?
Velocity已经提供了很完善的工具(velocity-tools),用它即可。下面是使用方法:
1、在Struts的配置文件(struts.xml)中,指定该工具的配置文件的位置。

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <struts>  
  2.     <constant name="struts.velocity.toolboxlocation" value="WEB-INF/toolbox.xml" />  
  3. </struts>  

2、修改该工具的配置文件,添加自己所需的工具(比如NumberTool)。

[html] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   
  3.     "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">  
  4. <toolbox>  
  5.     <tool>  
  6.         <key>NumberTool</key>  
  7.         <scope>application</scope>  
  8.         <class>org.apache.velocity.tools.generic.NumberTool</class>  
  9.     </tool>  
  10.     <tool>  
  11.         <key>NumericTool</key>  
  12.         <scope>application</scope>  
  13.         <class>com.yunlan.desktop.back.tool.NumericTool</class>  
  14.     </tool>  
  15. </toolbox>  

3、然后,在JSP页面里,即可使用该工具,进行各种格式化了。

[javascript] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $NumberTool.format("#0.00",$result)  

注意:如果Velocity自带的工具类,不能满足我们的需求,那么,可以使用自己定义的格式化类(比如上述配置里的NumericTool)。
1、自定义的NumericTool类的实现源码。

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.yunlan.desktop.back.tool;  
  2.   
  3. public class NumericTool {  
  4.     /** 
  5.      * 将浮点数小数,固定保留两位小数 
  6.      */  
  7.     public static String toFixedNumber(Double d) {  
  8.         if (d == null) {  
  9.             return "";  
  10.         }  
  11.         String valStr = String.format("%1$.2f", d);  
  12.         return valStr;  
  13.     }  
  14. }  

2、在JSP页面里,使用自定义的NumericTool类。

[javascript] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $NumericTool.toFixedNumber($result)  

日期的格式化,跟数值的格式,基本类似,具体可参考官方文档。
官方文档:http://velocity.apache.org/tools/devel/

From: http://blog.csdn.net/gaojinshan/article/details/38850721

猜你喜欢

转载自107x.iteye.com/blog/2176353