首页 > 技术文章 > FreeMarker模板引擎创建html例子

cbiwei 2017-06-08 16:23 原文

下载地址

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

freemaker创建html例子

从网上看到例子后,自己测试使用的代码.

package grenter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException; 
public class FreeMarkerTest {

	
	public static void main(String[]args) throws IOException, TemplateException{
		formStringCreateTemplate();
		formFileCreateTemplate();
		init();
		fromConfigCreateTemplate();
	}
	
	/**
	 * 从字符串创建模板对象
	 * 
	 * @date 2017年6月8日 下午3:53:26
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static void formStringCreateTemplate() throws IOException, TemplateException{
		String s = "用户名:${user},密码:${pwd}";
		// 创建模板
		Template template = new Template(null,new StringReader(s));
		// 执行插值,然后输出
		template.process(buildData(), new OutputStreamWriter(System.out));
	}
	
	/**
	 * 从文件创建模板
	 * 
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws TemplateException 
	 * @date 2017年6月8日 下午3:55:08
	 */
	public static void formFileCreateTemplate() throws FileNotFoundException, IOException, TemplateException{
		Template template = new Template(null,new FileReader(new File("/Users/user/Documents/temp/ftl/login.ftl")));
		
		// 执行插值,然后输出
		template.process(buildData(), new OutputStreamWriter(System.out));
	}
	
	/**
	 * 组建插值数据
	 * @date 2017年6月8日 下午4:16:45
	 * @return
	 */
	public static Map buildData(){
		Map map = new HashMap<String,String>();
		map.put("user", "user");
		map.put("pwd", "123456");
		return map;
	}
	public static FileWriter buildOutputStream() throws IOException{
		File file = new File("/Users/user/Documents/temp/ftl/login.html");
		return new FileWriter(file);
	}
	
	private static Configuration configuration;
	public static void init() throws IOException{
		configuration = new Configuration();
		configuration.setDirectoryForTemplateLoading(new File("/Users/user/Documents/temp/ftl/"));
		
	}
	/**
	 * 
	 * 
	 * @date 2017年6月8日 下午4:15:33
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static void fromConfigCreateTemplate() throws IOException, TemplateException{
		Template template = configuration.getTemplate("login.ftl");
		FileWriter writer = buildOutputStream();
		template.process(buildData(), writer);
		writer.close();
	}
	
}


推荐阅读