FreeMarker的认识及实例(二)

通过上一篇freemarker的认识及实例(一)让我们对于Freemarker有了基本的一些了解,下面是我写的一些代码,参考一下。

package com.bw.bean;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TestDemo {

    public static void main(String[] args) throws IOException, TemplateException {
        //创建Freemarker配置实例
        Configuration cfg=new Configuration();
        cfg.setDirectoryForTemplateLoading(new File("templates"));
        //创建数据模型
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("user", "hh");
        //一个随机数
        map.put("random", new Random().nextInt(100));
        //一个list集合
        List<Address> list=new ArrayList<Address>();
        list.add(new Address("河北","衡水"));
        list.add(new Address("河南","郑州"));
        list.add(new Address("山东","德州"));
        map.put("list", list);
        map.put("date1", new Date());
        //加载模板文件
        Template template=cfg.getTemplate("a1.ftl");
        //显示生成的数据
        Writer out=new OutputStreamWriter(System.out);
        template.process(map, out);
        out.flush();
        out.close();
    }

}  

a1.ftl的代码

<#list list as li>
    ${li.country}===${li.city}
</#list>
//获取到时间
${date1?string("yyyy-MM-dd HH:mm:ss")}
//用获取到的随机数进行if else 判断
<#if random gt 90>
     "及格了"
<#else>
     "不及格"
</#if>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值