By kswaughs | Thursday, November 19, 2015

FreeMarker Java Template Engine

FreeMarker is a Java based template engine to generate text output based on templates and changing data. The text output can be HTML web pages, e-mails, configuration files, source code, etc. Basically, Three components are involved based on the below activities.

1. Text format - How the data should look like [ Template ]
2. Data - what is the data to be generated in the required format [ Data Model ]
3. Output Generator - Read the template, pass the data model and get the text output [ Freemarker library ]

Templates are written in the FreeMarker Template Language (FTL), which is a simple, specialized language. Data Model is Simple Java objects to hold the chaging data. Freemarker library has set of predefined java classes which we use to get the output.

Lets go with a sample example, we have a banking customer who spends his card at several merchants and he wants to receive the list of transactions summary on weekly basis. Below steps show how to design the data model, template and how to use Freemarker library to get the output.

1. Create a Data Model Objects to hold Customer & its Transaction details.

Customer class
package com.poc.template;

import java.util.List;

public class Customer {
 
 private String name;
 
 private String cardNumber;
 
 private String dateRange;
 
 private List transList;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCardNumber() {
  return cardNumber;
 }

 public void setCardNumber(String cardNumber) {
  this.cardNumber = cardNumber;
 }

 public String getDateRange() {
  return dateRange;
 }

 public void setDateRange(String dateRange) {
  this.dateRange = dateRange;
 }

 public List getTransList() {
  return transList;
 }

 public void setTransList(List transList) {
  this.transList = transList;
 }
}
Transaction Class
package com.poc.template;

public class Transaction {
 
 private String type;
 
 private String merchant;
 
 private String amount;

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 public String getMerchant() {
  return merchant;
 }

 public void setMerchant(String merchant) {
  this.merchant = merchant;
 }

 public String getAmount() {
  return amount;
 }

 public void setAmount(String amount) {
  this.amount = amount;
 }
}

Design your template 'transSummaryTemplate.ftl'

Dear ${name},

Below are your card transaction details for the week '${dateRange}'.

Account Number : ${cardNumber}

============================================
S.No    Merchant            Type     Amount
============================================
<#list transList as trans>
${trans_index  + 1}.    ${trans.merchant}      ${trans.type}      ${trans.amount}
</#list>

First Load the template object from Freemarker Configuration object. Build the customer object with the transaction details. In this example the output content is generated as file as well as String content. When you are saving as some HTML file, you can directly display into some web page. When you generate as String, You can pass this string as email content to some Email System which will take care of sending process.

FreeMarkerExample
package com.cog.template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

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

public class FreeMarkerExample {

 public static void main(String[] args) {

  // Freemarker configuration object
  Configuration cfg = new Configuration();
  try {
   // Load template from source folder
   Template template = cfg
     .getTemplate("src/resources/templates/transSummaryTemplate.ftl");

   // Build the data-model
   Customer customer = new Customer();

   // Build customer details
   customer.setCardNumber("232487899767001");
   customer.setName("kswaughs");
   customer.setDateRange("Nov 16 2015 - Nov 22 2015");

   // Build transaction details
   List trans = buildTransactions();
   customer.setTransList(trans);

   // File output
   Writer file = new FileWriter(new File(
     "src/resources/templates/customer.html"));
   template.process(customer, file);
   file.flush();
   file.close();

   // String Output
   StringWriter strOut = new StringWriter();
   template.process(customer, strOut);
   strOut.flush();
   System.out.println(strOut.toString());
   // send strOut object as content to Send Email System. 

  } catch (IOException e) {
   e.printStackTrace();
  } catch (TemplateException e) {
   e.printStackTrace();
  }
 }

 private static List buildTransactions() {
  List trans = new ArrayList();
  // First transaction
  Transaction atmTrans = new Transaction();
  atmTrans.setMerchant("SBI ATM, Gajuwaka");
  atmTrans.setType("ATM");
  atmTrans.setAmount("3000");
  trans.add(atmTrans);

  // Second transaction
  Transaction cardTrans = new Transaction();
  cardTrans.setMerchant("IMAX, Hyderabad");
  cardTrans.setType("SWIPE");
  cardTrans.setAmount("500");
  trans.add(cardTrans);
  
  return trans;
 }
}

Output is

Dear kswaughs,

Below are your card transaction details for the week 'Nov 16 2015 - Nov 22 2015'.

Account Number : 232487899767001

============================================
S.No    Merchant            Type     Amount
============================================
1.    SBI ATM, Gajuwaka      ATM      3000
2.    IMAX, Hyderabad      SWIPE      500

Use Below maven dependency in your pom.xml to get this Freemarker template

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

Recommend this on


No comments:

Post a Comment