您的位置:首页 > 其它

Velocity模板引擎试用

2013-11-07 19:10 134 查看

在框架处理日志的时候,支持配置方式生成日志。日志内容可以根据一定的规则来生成。这里就可以使用Velocity了。

 

下面针对常用的几种类型进行测试

1)map

Map map = new HashMap();
map.put("abc", "def");
context.put("param", map );
String commentEL = "$param.abc";

 结果输出为def

 

2)dto

ServiceLogDto dto = new ServiceLogDto();
dto.setPartyCode("logCode");
context.put("param", dto );
commentEL = "$param.partyCode";

  结果输出为logCode

 

3)[ ] 数组

ServiceLogDto [] dtos = new ServiceLogDto[2];
dtos[0]=dto;
dtos[1]=new ServiceLogDto();
dtos[1].setPartyCode("testCode");
context.put("param", dtos );
commentEL = "#foreach($o in $param)$o.partyCode #end";

 结果输出为 logCode  testCode

 

4)list

List list = new ArrayList();
list.add(dto);
ServiceLogDto dto2 = new ServiceLogDto();
dto2.setPartyCode("test2");
list.add(dto2);
context.put("param", list );
commentEL = "#foreach($o in $param)$o.partyCode #end";

 输出为 logCode  test2

 

 

基本的类型都能用,即便有复杂的类型也可以在数据源这边转化一下。

附上上面代码片段的前后备用

VelocityEngine engine = new VelocityEngine();
engine.init();
VelocityContext context = new VelocityContext();

/////some code below

String re= evaluate(engine, context, commentEL );
System.out.println(re);

///////////////////////////////////////////////////////////////

private static String evaluate(VelocityEngine engine, VelocityContext context, String expr) {
if (expr == null || expr.trim().length() == 0) {
return "";
}
try {
CharArrayWriter writer = new CharArrayWriter();
engine.evaluate(context, writer, "", expr);
return writer.toString();
}
catch (Exception e) {
return expr;
}
}

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: