freemarker简单学习

一、首先导入jar包,freemarker.jar

二、事例:

     1、最简单的freemaker


package cn.com.freemaker;

import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Template;

public class TestFreemarker001 {
    public static void main(String[] args) throws Exception{
            //创建一个模版对象
            Template t = new Template(null, new StringReader("用户名:${userName};URL:    ${url};姓名:  ${cname}"), null);
            //创建插值的Map
            Map map = new HashMap();
            map.put("userName", "findJob");
            map.put("url", "http://www.baidu.com/");
            map.put("cname", "百度");
            //执行插值,并输出到指定的输出流中
            t.process(map, new OutputStreamWriter(System.out));
    }
}
    2、使用模板生成html文件

package cn.com.freemaker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

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

public class TestFreemarker002 {
    private Configuration cfg;//配置模板信息的对象

    public void init() throws Exception {
            cfg = new Configuration();
            //设置模版文件夹位置
            cfg.setDirectoryForTemplateLoading(new File("C:\\mine\\Programs\\eclipse\\workplace\\A_freemaker\\src"));
    }

    public void process() throws Exception {
            //构造map用于数据的封装
            Map map = new HashMap();
            map.put("username", "鎏董");
            map.put("url", "http://www.51job.com/?from=baidupz");
            map.put("companyName", "前程无忧");
            //创建模版对象
            Template t = cfg.getTemplate("freemarker.ftl");
            //将流输入到指定的文件中
            t.process(map, new OutputStreamWriter(new FileOutputStream(new File("C:\\mine\\Programs\\eclipse\\workplace\\A_freemaker\\WebContent\\myhtml.html"))));
    }

    public static void main(String[] args) throws Exception {
            TestFreemarker002 hf = new TestFreemarker002();
            hf.init();
            hf.process();
    }
}
    模板文件freemarker.ftl

<html>
<head>
	<meta charset="UTF-8">
    <title>Welcome!</title>
</head>
<body>
    <h1>Welcome ${username}!</h1>
    <p>Our latest product:
    <a href="${url}">${companyName}</a>!
</body>
</html> 
   生成的html文件,myhtml.html

<html>
<head>
	<meta charset="UTF-8">
    <title>Welcome!</title>
</head>
<body>
    <h1>Welcome 鎏董!</h1>
    <p>Our latest product:
    <a href="http://www.51job.com/?from=baidupz">前程无忧</a>!
</body>
</html> 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值