FreeMarker最简单的例子(1)



一、通过文件来创建模版对象,并执行插值操作

文件结构为:

Test.java中的代码为:

package com.abc;

 

import freemarker.template.Configuration; 

import freemarker.template.Template; 

import java.io.File; 

import java.io.OutputStreamWriter; 

import java.util.HashMap; 

import java.util.Map; 

 

public class Test { 

    public static void main(String[] args) throws Exception { 

        //创建一个Configuration实例 

        final Configuration cfg;   

        cfg = new Configuration(); 

        //设置FreeMarker的模版文件夹位置 

        cfg.setDirectoryForTemplateLoading(new File("D:\\workspace\\freemarkertest\\src\\com\\abc"));

        Map<String, String> map = new HashMap<String, String>(); 

        map.put("user", "Zheng");

        map.put("website", "金额宝"); 

        map.put("url", "http://www.jebao.net/"); 

        //创建模版对象 

        Template t = cfg.getTemplate("test.ftl"); 

        //在模版上执行插值操作,并输出到制定的输出流中 

        t.process(map, new OutputStreamWriter(System.out)); 

    } 

}

Test.ftl中的代码为:

<html> 

<head> 

    <title>Welcome!</title> 

</head> 

<body> 

    <h1>Welcome ${user}!</h1> 

    <p>Our latest product: 

    <a href="${url}">${website}</a>! 

</body> 

</html> 

 

尊敬的用户你好!

用户名:${user}

URL:    ${url}

网站:  ${website}

运行结果为:

</head>

<body>

    <h1>Welcome Zheng!</h1>

    <p>Our latest product:

    <ahref="http://www.jebao.net/">金额宝</a>!

</body>

</html>

 

尊敬的用户你好!

用户名:Zheng

URL   http://www.jebao.net/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值