第一步
package com.air.freemarker;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
public class Test {
public static void main(String[] args) throws Exception{
//模板路徑
String dir = Test.class.getResource("/").getPath().split("WEB-INF")[0] + "freemarker";
Configuration cfg = new Configuration();
//加載freemarker模板文件
cfg.setDirectoryForTemplateLoading(new File(dir));
//設置對象包裝器
cfg.setObjectWrapper(new DefaultObjectWrapper());
//設計異常處理器
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
//定義並設置數據
Map<String, String> data = new HashMap<String, String>();
data.put("persion", "小吳");
//獲取指定模板文件
Template template = cfg.getTemplate("test.ftl");
//定義輸入文件,默認生成在工程根目錄
Writer out = new OutputStreamWriter(new FileOutputStream("test.html"),"GBK");
//最後開始生成
template.process(data, out);
System.out.println("successful");
}
}
第二步
在webRoot下建立freemarker文件夾
在文件夾中建立test.ftl文件代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
The first test: ${persion}
</body>
</html>
第三步
運行代碼,你就會在你的WebRoot目錄下出現test.html文件