FreeMarker入门程序实例

一个简单的运用freemark的入门程序:

1.引入freemarker的jar包。
2.创建test.ftl文件。
内容为:

<html> 
<head> 
    <title>Welcome!</title> 
</head> 
<body> 
    <h1>Welcome ${user}!</h1> 
    <p>Our latest product: 
    <a href="${url}">${name}</a>! 
</body> 
</html> 

尊敬的用户你好: 
用户名: ${user}; 
URL:    ${url}; 
姓名:  ${name}

3.创建java项目,新建Test.class类:

package com.zjy.test;

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

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


public class Test {

    //C:\Users\Administrator\Desktop
    private Configuration config;   //配置模板对象

    public void init() throws Exception{
        //初始化FreeMarker配置
        //创建一个Configuration实例
        config = new Configuration();
        //设置FreeMarker模板文件夹位置
        config.setDirectoryForTemplateLoading(new File("C:\\Users\\Administrator\\Desktop"));
    }

    public void process() throws Exception{
        //构造填充数据的Map
        Map map = new HashMap();
        map.put("user", "tom");
        map.put("url", "www.baidu.com");
        map.put("name", "百度");
        //创建模板对象
        Template t = config.getTemplate("test.html");
        t.process(map, new OutputStreamWriter(System.out));
    }

    public static void main(String[] args) throws Exception {
        Test t = new Test();
        t.init();
        t.process();
    }
}

运行结果为:

<html> 
<head> 
    <title>Welcome!</title> 
</head> 
<body> 
    <h1>Welcome tom!</h1> 
    <p>Our latest product: 
    <a href="www.baidu.com">百度</a>! 
</body> 
</html> 

尊敬的用户你好: 
用户名: tom; 
URL:    www.baidu.com; 
姓名:  百度
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值