In this post, I am going to create 'user.ftl' file which has user template data and merge the template with fields from user object using Freemarker.
Step 1: Create user.ftl file under src/main/resources/templates folder.
user.ftl
name: ${user.name}
age: ${user.age}
city: ${user.city}
Step 2: Define a model class that holds user information.
User.java
package com.sample.app.templates.model;
public class User {
private String name;
private int age;
private String city;
public User(String name, int age, String city) {
super();
this.name = name;
this.age = age;
this.city = city;
}
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 getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Step 3: Create 'FreeMarkerUtil' class that takes a model object and freemarker template file as input and merge them.
FreeMarkerUtil.java
package com.sample.app.util;
import java.io.StringWriter;
import java.util.Locale;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
public class FreeMarkerUtil {
private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);
static {
FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
StringWriter stringWriter = new StringWriter();
Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);
template.process(modelObject, stringWriter);
return stringWriter;
}
}
Step 4: Define UserPopulator class like below.
UserPopulator.java
package com.sample.app;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import com.sample.app.templates.model.User;
import com.sample.app.util.FreeMarkerUtil;
public class UserPopulator {
public static void main(String args[]) throws Exception {
Map<String, Object> modelObject = new HashMap<String, Object>();
modelObject.put("user", new User("Krishna", 31, "Bangalore"));
StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "user.ftl");
System.out.println(stringWriter);
}
}
Run UserPopulator, you will see below messages in the console.
name: Krishna age: 31 city: Bangalore
As you see the output, placeholders ${user.name}, ${user.age}, and ${user.city} are populated with actual values from the model object.
You can visualize this data model as a tree kind of structure.
(root) | +- user | +- name +- age +- city
No comments:
Post a Comment