freemarker简单学习

来源:互联网 发布:知乎运营 编辑:程序博客网 时间:2024/06/05 15:47

一、首先导入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
原创粉丝点击