Document Templating or Mail Merge

20 Jan

INTRODUCTION

Document templating or mail merge is the process of using a template document to produce the same document over and over changing just a few variables. Mail merge probably got its name because it is traditionally used for sending form letters to a bunch of a people in mailing list database, changing the person’s name and address each time the document is generated.
 
Today we don’t just have form letters, but we also have SPAM! So how can we easily generate these form letter or pieces of SPAM in Java? With Apache Velocity!
 
Apache Velocity can do much more than generating form letters or SPAM. They have tools for using Velocity templates for generating web pages, tools for modifying XML documents, and even tools for generating documents for online viewing or printing. In this post I focus only on simple document templating for the purposes of generating e-mails. SOP4J in no way advocates sending SPAM messages; however, this type of templating can be very useful in generating welcome e-mails for websites and other non-SPAM e-mails. Please do not send unsolicited e-mails to people!
 

THE VELOCITY ENGINE

The Velocity Engine is what is used to do the templating for all of the Velocity projects. At its most basic, the Velocity Engine takes variables denoted with a dollar sign ($) and replaces them with the assigned variable in the provided context. However, it also provides much more advanced directives such as If-Else statements, Foreach loops, includes, and macros.
 
The following code is used to configure the Velocity Engine to use the classpath resource loader and log4j as the logger.
With the engine configured, the next thing to do is setup the context.
In this example I show 3 different values set in the context:
  1. simple UserBean
  2. string literal
  3. list of ArticleBeans

Velocity has directives for easily handling all of these types! Once the context is configured, the template is loaded and merged.

THE VELOCITY TEMPLATE LANGUAGE

The Velocity Template Language has a number of different directives to do just about anything you’d want to do in a template. The reference guide and user guide will help you navigate your way through the VTL. The template used in the program is shown below.
The output from merging the above code and template is as you’d expect:
That is it! As you can see the Velocity Engine is quite powerful and can provide all of the templating or mail merging features needed for most projects. The next time you find yourself either writing a lot of text inside your Java code, or doing find/replace on special notation in text, trying using the Velocity Engine instead!
 
As always, you can find the full source, if you have any questions, please post them in the comments. If you have bug fixes or improvements, please fork and make a pull request.
 
Thanks for reading…

Leave a Reply

Your email address will not be published. Required fields are marked *