freemarker使用map替换ftl中相关值

ftl文件demo01.ftl

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

java类  Demo01.java

package demo01;

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 Demo01 {

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

Configuration cfg = new Configuration();
File file = new File(Demo01.class.getResource("/").getPath().substring(1)+"template");
System.out.println(file.getPath());

//设置模板文件所在目录
cfg.setDirectoryForTemplateLoading(file);

 //构造填充数据的Map 

Map map = new HashMap(); 
map.put("user", "lavasoft"); 
map.put("url", "http://www.baidu.com/"); 
map.put("name", "crd");

//设置模板文件名
Template tmp = cfg.getTemplate("demo01.ftl");
tmp.process(map, new OutputStreamWriter(System.out));


}

}
java

 

目录结构

 

 执行后台打印:

 所需jar包

 

posted @ 2019-06-25 14:52  爱跳舞的程序员  阅读(858)  评论(0编辑  收藏  举报