velocity(vm)模板引擎

本文介绍如何使用Apache Velocity模板引擎创建简单的输出示例。通过Java代码设置Velocity环境,并加载模板文件,最终生成包含变量数据的HTML文本。演示了基本的Velocity指令用法,如变量设置、循环等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

velocity是apache基金会的项目。

public class HelloVelocity { 
 public static void main(String[] args) { 
 VelocityEngine ve = new VelocityEngine(); 
 ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
 ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); 
 
 ve.init(); 
 
 Template t = ve.getTemplate("hellovelocity.vm"); 
 VelocityContext ctx = new VelocityContext(); 
 
 ctx.put("name", "velocity"); 
 ctx.put("date", (new Date()).toString()); 
 
 List temp = new ArrayList(); 
 temp.add("1"); 
 temp.add("2"); 
 ctx.put( "list", temp); 
 
 StringWriter sw = new StringWriter(); 
 
 t.merge(ctx, sw); 
 
 System.out.println(sw.toString()); 
 } 
}

vm文件如下

#set( $iAmVariable = "good!" ) 
Welcome $name to velocity.com 
today is $date. 
#foreach ($i in $list) 
$i 
#end 
$iAmVariable

输出结果如下
Welcome velocity to velocity.com
today is Sun Mar 23 19:19:04 CST 2014.
1
2
good!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值