一、freemarker的使用步骤
0.添加freemarker依赖的jar包
1.创建一个configuration对象
2.载入模板路径
3.设置configuration对象的默认编码方式
4.根据指定的模板文件创建模板对象
5.创建数据集
6.创建一个Writer对象,指定生成的文件路径和文件名
7.调用模板的process方法生成静态文件
8.关闭输出流
二、具体实例
public class TestFreemarker {
public static void main(String[] args) throws IOException, TemplateException {
//1.创建configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//2.设置模板载入路径
configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\tanjie\\Desktop\\taotao商城new\\test\\src\\main\\webapp\\WEB-INF\\ftl"));
//3.设置默认编码
configuration.setDefaultEncoding("utf-8");
//4.根据制定模板文件创建模板对象
Template template = configuration.getTemplate("hello.ftl");
//5.创建数据集
Map<String, String> root = new HashMap<String, String>();
root.put("hello", "hello, freemarker");
//6.创建一个writer对象,指定生成文件路径和文件名
Writer out = new FileWriter(new File("C:\\Users\\tanjie\\Desktop\\html\\hello.html"));
//7.调用模板对象的process方法生成静态文件
template.process(root, out);
//8.关闭输出流
out.flush();
out.close();
}
}