Properties
FreeMarker is a java based template engine for complex template processing.
This requires the library freemarker-2.3.16.jar to be in classpath.
The following example shows accessing bean properties.
package com.bethecoder.tutorials.freemarker.common;
public class Student {
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.freemarker.tests;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import com.bethecoder.tutorials.freemarker.common.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class PropertiesTest {
/**
* @param args
* @throws IOException
* @throws TemplateException
*/
public static void main ( String [] args ) throws IOException, TemplateException {
//Get template from classpath
Configuration cfg = new Configuration () ;
cfg.setClassForTemplateLoading ( PropertiesTest.class, "/" ) ;
Template template = cfg.getTemplate ( "props.ftl" ) ;
//Prepare data model
Map<String, Object> dataModel = new HashMap<String, Object> () ;
dataModel.put ( "std" , new Student ( "Sriram" , 2 , "Chess" )) ;
//Merge template and data
OutputStreamWriter output = new OutputStreamWriter ( System.out ) ;
template.process ( dataModel, output ) ;
}
}
It gives the following output,
Name : Sriram
Age : 2
Hobby : Chess