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>

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));


}

}

目录结构

 执行后台打印:

猜你喜欢

转载自www.cnblogs.com/rdchen/p/11082812.html