Kent has posted 1 posts at DZone. View Full User Profile

Simple Templating System for Java

  • submit to reddit

A templating system allows generating the text for HTML, emails, SQL, etc. without hardcoding the text in Java. This greatly improves the managability of your Java code and makes it much easier to make changes. While the templating system presented below is simple to implement, it still supports variable substitutions, condition logic, loops, etc. This templating system requires Jelly and is implemented in the provided JellyScript Wrapper Class.

Let's say you have a welcome email that should look something like this...

Hello, Kent, thanks for creating a Trendics account at
Your new user name and password is...
   User: kent13600
   Password: my.secret
Be sure to checkout our webmaster tools at

- Trendics Support Team

Instead of hardcoding this text within a Java class, you can use the provided JellyScript Wrapper Class to define a template that looks like this...

Hello<jelly:if test='${!empty FirstName}'>, ${FirstName}</jelly:if>, thanks for creating a
Trendics account at
Your new user name and password is...
User: ${UserName}
Password: ${Password}
Be sure to checkout our webmaster tools at
- Trendics Support Team

The LastName and Password variables are simply substituted at the appropriate locations. The <jelly:if test='${!empty FirstName}'>, ${FirstName}</jelly:if> logic is only adding a comma and the FirstName if the FirstName is not blank.

As another example, you can use this templating system to generate SQL...

FROM Employee
WHERE State='${State}'
<jelly:if test='${!empty City}'>
AND City='${City}'

In the SQL template above, a State filter parameter is required and a City filter parameter may optionally be included.

The examples above did only simple variable substitution and a bit of conditional logic; however, Jelly supports a whole range of tags supporting various types of logic constructs including loops, creating Java objects, calling methods on Java objects, etc. (see here). The Jelly tags are very similar to JSTL tags commonly used in JSP pages -- this makes the learning curve easy for developers already familiar with JSTL.

Here is an example of the Java code necessary to execute a template...

 public static void main(String[] args) {

if (logger.isLoggable(Level.FINE)) logger.fine("main()");
try {
// Create a template
final String text = "";
text += "Hello<jelly:if test='${!empty FirstName}'>";
text += ", ${FirstName}</jelly:if>, ";
text += "thanks for creating a Trendics account ";
text += "at ";
text += "Your new user name and password is...\n";
text += "\n";
text += " User: ${UserName}\n";
text += " Password: ${Password}\n";
text += "\n";
text += "Be sure to checkout the instant website ";
text += "speed check at\n";
text += "\n";
text += "- Trendics Support Team\n";

// Create the JellyScript instance
final JellyScript jellyScript = new JellyScript(text);

// Create the variables needed by the template
final Map<String, Object> variables = new HashMap<String, Object>();
variables.put("FirstName", "Kent");
variables.put("UserName", "kent13600");
variables.put("Password", "my.secret");

// Execute the script to merge the variables with the template
final String result = jellyScript.execute(variables);
catch (Exception e) {
logger.log(Level.SEVERE, "main()", e);

Note that defining the template within Java code sort of defeats a key benefit of templating -- you would normally define your templates within an XML configuration file or store the templates in their own files.

If you need a more robust templating solution, take a look at the Apache Velocity Project.

Published at DZone with permission of its author, Kent Johnson.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Tim Thomas replied on Mon, 2008/07/07 - 3:41pm

I've used this in the past and it's pretty slick. Very nice for doing template replacement in configuration files and the like.

It should be noted that you should never generate SQL as in the example above or you will be vulnerable to SQL injection attacks.

Jay Spring replied on Mon, 2008/07/07 - 3:57pm

does this support  i18n?

is there a way I could load tokens from a resource bundle? 

Martin Vaněk replied on Tue, 2008/07/08 - 3:37am

Jelly's xml programming is sick idea.

Jose Maria Arranz replied on Wed, 2008/07/09 - 2:16am in response to: Martin Vaněk

Why? XML of Spring, JSP and JSF tagslibs mixed with EL they all are imperative pseudocode. What is the difference? OK, Jelly is a general purpose.

In fact Jelly is very interesting for templating in web applications. This is not my approach (I'm the author of ItsNat) but I see Jelly interesting if you follow the route of view-is-source-code (the view is executable) typical of the most important frameworks out there.

One important Jelly feature is it can embedded easily in any application so you can use it as your HTML renderer.


Jesper De Jong replied on Wed, 2008/07/09 - 6:01am

The SQL example does not look very smart to me.


Instead of generating SQL statements like this, use PreparedStatement. Advantages of PreparedStatement are that it's not as vulnerable to SQL injection attacks, and if you prepare a statement once and re-use it, the database (driver) will only have to parse the SQL once, which is good for performance.


I can see the usefulness of a templating engine, but don't use it for SQL like this.

Martin Vaněk replied on Fri, 2008/07/11 - 5:33am in response to: Jose Maria Arranz

Configuration yes, programming no. Only exception could be html/xml tag based templating languages, but surely not SQL.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.