FreeMarkerのHello World

1680 ワード


      MyEclipse       Java Project,             templates,
 templates         testFreeMarker.ftl,        freemarker.jar    :
welcome ${customer} to sunyang!

  java  
package com.test.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

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

public class TestFreeMarker {
	
	private Configuration configuration;
	
	public void init() {
		configuration = new Configuration();		
		try {
			configuration.setDirectoryForTemplateLoading(new File("templates"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void process() {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("customer", "Jone");
		Template template;
		try {
			template = configuration.getTemplate("testFreeMarker.ftl");
			template.process(data, new OutputStreamWriter(System.out));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		TestFreeMarker tfm = new TestFreeMarker();
		tfm.init();
		tfm.process();

	}

}