一、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();
}
}