Velocity模板引擎试用

在框架处理日志的时候,支持配置方式生成日志。日志内容可以根据一定的规则来生成。这里就可以使用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;
        }
    }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值