Searching...
Friday, 21 March 2014

Java Template engine Freemarker simple example

08:58

1. Create a maven project and add below dependency

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

2. Create a Template file and placed in to project folder (helloworld.flt)

Hello world Mr ${name}

3. Create a main class (FreeMarkerExample.java)

package com.pretech;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerExample {
	public static void main(String[] args) {
		try {
			Configuration config = new Configuration();
			Map<String, String> root = new HashMap<String, String>();
			root.put("name", "PRETECH");
			Template template;
			template = config.getTemplate("helloworld.ftl");
			StringWriter out = new StringWriter();
			template.process(root, out);
			System.out.println(out.getBuffer().toString());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}

4. Output



Hello Mr PRETECH


0 comments: