使用freemark進行模板轉換爲報文

1 .引入freemarker包

    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.22</version>
    </dependency>

2 .準備freemarker模版 :模版名:xx.ftl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${user.id}-----${user.name}-----${user.age}</h1>
<#if user.age lt 12>
${user.name}還是一個小孩
<#elseif user.age lt 18>
${user.name}快成年
<#else>
${user.name}已經成年
</#if>
</body>
</html>

    新建一個templete文件夾或者包,將xx.ftl放到templete下。    

    新建的templete放到項目目錄下:src/main/resources 或 src/main/java 目錄下
都可以。

 

   3 .map數據模型

Map<String,Object> root=new HashMap<String,Object>();
User user = new User();
user.setId(1011);
user.setName("汪峯");
user.setAge(52);
root.put("user", user);//在ftl中要賦值的變量
fu.fprint("03.ftl", root, "01.html");

   4 .數據合併到模板

package artro.freeMarker;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {

	public Template getTemplate(String name) {
		try {
			// 通過Freemarker的Configuration讀取相應的ftl
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);// 這裏是對應的你使用jar包的版本號
			// 第二個參數 爲你對應存放.ftl文件的包名
			configuration.setClassForTemplateLoading(this.getClass(), "/templete");
			Template template = configuration.getTemplate(name);
			return template;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void print(String name, Map<String, Object> data) {
		// 通過Template可以將模版文件輸出到相應的文件流
		Template template = this.getTemplate(name);
		try {
			template.process(data, new PrintWriter(System.out));// 在控制檯輸出內容
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 輸出HTML文件
	 * 
	 * @param name
	 * @param root
	 * @param outFile
	 */
	public void fprint(String name, Map<String, Object> data, String outFile) {
		FileWriter out = null;
		try {
			// 通過一個文件輸出流,就可以寫到相應的文件中,此處用的是絕對路徑
			out = new FileWriter(new File("D:/new_works/freeMarker/src/static/"
					+ outFile));
			Template temp = this.getTemplate(name);
			temp.process(data, out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

5 .常用的語法

1,通用插值:${expr};

2,數字格式化插值:#{expr}或#{expr;format}

3,循環讀取集合:<#list student as stu>${stu}<br/></#list> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章