EDITING BOARD
RO
EN
×
▼ BROWSE ISSUES ▼
Issue 23

Template Engines for Java Web Development

Dănuţ Chindriş
Java Developer
@Elektrobit Automotive



PROGRAMMING

In many projects we deal with situations when we have to process text, generate reports, scripts or source code. Many times these problems can be solved with the help of certain tools called template processors. However, the most common scenario for using template processors is that of web development, where the need to separate business logic from the presentation layer was identified.

When it comes to web applications developed using Java technologies, JavaServer Pages was the standard for the presentation layer for a long time. Among many other things JavaServer Pages has the features of a template processor. The biggest shortcoming of this technology is the possibility to insert business logic in the presentation code. Thus, we can insert into the JSP document scriptlets or even Java code blocks. Although this can help us in certain situations, the code becomes rapidly complex and hard to maintain. Moreover, this approach doesn"t follow the MVC design pattern.

Because of shortcomings such as this one, JSP lost many followers in favor of other template engines, which are used in more and more projects, increasing the developers" productivity and the quality of the products. The projects that we will talk about help us to easily create dynamic content, combining the templates with the data model in order to produce result documents. The templates are written in a templating language and the resulting documents can represent any formatted text.

Besides the well-known processors, such as Apache Velocity and FreeMarker, during the recent years a variety of new template engines was launched. In this article we will analyze four products available freely for commercial use, trying to make a comparison between them.

Spring MVC and Template Processors

When we plan to develop a web application using Java technologies, one of the first things we do is to choose a MVC framework. Experience has proven that Spring MVC is one of the most popular web frameworks, and in this article we will analyze the use of template engines from their integration point of view. In order to illustrate a few features of each presented processor, we will develop a simple web application which will contain two pages: one that displays a list of products and another that displays the details of a product.

Apache Velocity

Velocity is a project distributed under the Apache Software License, which benefits from great popularity among the Java applications developers. Although it is often used within the web context, we are not limited to using the product only for this kind of projects. It can be used either as a standalone utility for source code and reports generation or as an integrated component of other systems.

Like other template engines, Velocity was designed to enable the webmasters and the Java developers to work in parallel. Thus Velocity helps us separate the Java code from the web pages" code, offering a good alternative to JSP.

Velocity Template Language

Apache Velocity enjoys its own scripting language called Velocity Template Language (VTL) which is powerful and flexible. The authors of Apache Velocity proudly advertise that their product"s flexibility is limited only by the user"s creativity. VTL was created to offer the simplest and cleanest way for inserting dynamic content into a web page.

Velocity uses references to encapsulate dynamic content into web pages, and variables represent one of these references types. These are able to reference objects defined within the Java code or can receive values inside the web page through a VTL declaration. Such an instruction begins with a # character as we can see in the following example:

#set( $magazineUrl = "http://www.todaysoftmag.com/" )

Spring MVC Integration

Spring MVC natively supports the template engine we are talking about and consequently their integration is a trivial process. Assuming that we are using Maven for creating the project, we choose the maven-archetype-webapp archetype from the org.apache.maven.archetypes group. Without listing all necessary Maven dependencies, we have to mention that we need the following artifacts from the org.apache.velocity group: velocity and velocity-tools. The source code of the example project can be downloaded from the following URL: https://springvelocity.googlecode.com/svn/trunk.

After we have declared in web.xml the DispatcherServlet servlet which will handle all requests and we have defined the servlet-context.xml file with all its Spring MVC specific elements, we can declare the beans needed for working with Velocity. First of all we need a bean with the id velocityConfig to whom we will transfer the relative path where the templates for the application"s pages will be placed:

Then we declare a view resolver which receives several properties. The class that will represent the type of this bean has to implement the ViewResolver interface and its main purpose is to find the views by name. The most interesting property of this bean is layoutUrl. The value of this property is the name of the template that will set the general layout:

Velocity has also the ability to cache the templates that are being used. This is specified by the cache property.

Now that we have configured the application so that the presentation layer is represented by Velocity templates, we can see what these templates look like. The most interesting part of the template that determines the general layout is the presence of the $screen_content special variable. This variable will contain at runtime the processing result of the template that corresponds to the view returned by the Spring MVC controller. In our application"s case there is only one controller which is able to return either the list view or the details view. The template corresponding to the list view is list.vm and has the following content:

In the above block we can notice how a collection is iterated and how the objects" properties from the model are accessed through VTL.

Advantages and Disadvantages

Being one of the most popular projects as far as template processors are concerned Velocity benefits from a well-established community support. Also the documentation from the official website is rich and there are many articles that answer various questions. In addition, there are a few books dedicated to Apache Velocity or books that discuss a few features of it. If these resources are not enough, there is a mailing list with a rich archive that we can subscribe to.

There is a variety of aspects that can convince us to choose this product for our next project: Velocity is a powerful, flexible and feature rich processor. There are some developers that state this is the most powerful tool of this kind on the market.

Another strong point of this project is that besides Velocity Engine it is composed of several subprojects: Tools (tools and infrastructure elements useful for web applications development and more), Anakia (XML documents transformation), Texen (text generation), DocBook Framework (documentation generation), DVSL (Declarative Velocity Style Language -XML transformations).

When it comes to IDE support, Velocity benefits from a series of plug-ins developed by members of the community. These plug-ins are dedicated to a few IDEs such as Eclipse, NetBeans, IntelliJ IDEA, to name only the most popular. Many of these plug-ins offer syntax highlighting and even auto-completion. For developing the example presented in this article we used Velocity Edit for Eclipse.

As we showed in a previous paragraph Spring MVC integration is easy. Also the Spring MVC distribution contains a library with macros for binding support and form handling. These tools are valuable for web applications development.

Although it is the most popular template engine within the Java universe, Apache Velocity didn"t benefit from any release from November 2010 when the 1.7 version of the core was released. The project is still active but the community seems to be pleased with the functionalities already implemented and there is no release planned yet.

Velocity is a project heavily contributed to, becoming a complex product, intimidating for new users. The syntax is somehow cumbersome and writing templates without help from an IDE that supports the VTL syntax can be a nightmare.

FreeMarker

FreeMarker is a product that has reached maturity, distributed under a BSD license. Similar to the Apache Velocity project, FreeMarker offers complex functionalities designed for assisting web developers. It was designed for efficiently generating HTML pages, and not only that. Furthermore as the creators of the project state, this is a generic software product that can be used for text generation, ranging from HTML to source code.

FreeMarker Template Language

For the template description, FreeMarker provides us with a strong templating language, called FreeMarker Template Language. With FTL we can define expressions, functions and macros within the templates that we write. Furthermore, we also have the possibility to use a rich library with predefined directives that give us the possibility to iterate data collections, include other templates, and much more. We will continue by presenting an example of a FTL directive that assigns a value to a variable:

<#assign magazineUrl = "http://www.todaysoftmag.com/">

We can clearly see that in the FreeMarker specific templating language, the predefined directives are called by using the following syntax: <#directivename parameters>, the macros can be called like this: <@macro parameters> and the expressions are written in this manner: ${expression}.

Spring MVC Integration

Just like in Apace Velocity"s case, FreeMarker benefits from support for Spring MVC integration straight from the web framework"s creators. This way, the Spring MVC distribution offers us a ViewResolver implementation, but also a macro library for binding support and form handling.

By using the same way to create a Spring MVC + FreeMarker application as with Apache Velocity, we can see that the only modifications that we need to do are in the Spring MVC configuration file and in the templates. Actually, we will see that this is true also when we will talk about the Thymeleaf and Rythm projects. Also, the Maven dependency freemarker from the group org.freemarker is needed. The source code for the example project can be downloaded from the following URL: https://springfreemarker.googlecode.com/svn/trunk.

In the servlet-context.xml file we replace the configuration bean and the view resolver bean. The most interesting aspect of these XML elements is the property that has the auto_import key, which allows us to import the macros into all our FTL files. The macros are defined in the spring.ftl file, which is offered by the Spring MVC distribution. They are accessible through the the spring alias:

/spring.ftl as spring

The template that belongs to the list view is represented in the list.ftl file. Its most relevant part is the following:

<#include "header.ftl" />

Products

<#include "footer.ftl" />

In this template we can see how the content of another template can be included, how we can iterate over a collection of objects, and how we can write an FTL expression.

Advantages and Disadvantages

The FreeMaker project benefits from an extensive documentation, the official site consisting of a rich user manual from which both programmers and designers can extract a lot of useful information. Also, there is a discussion mailing list, but the users are encouraged to look for help on Stack Overflow, by asking questions marked with the "freemaker" tag. Although FreeMaker is a popular template engine, up till now a single book dedicated to it has been published.

FreeMarker offers us a complete templating language and is relatively easy to comprehend. It can be said that the competition between it and Velocity is pretty tight, being a product that has reached maturity, ready to be integrated in enterprise projects. Furthermore, similarly to the project presented previously, FreeMarker offers template caching mechanisms.

On the official page there is a list of plug-ins for different programming environments. For the example presented in this article we"ve used the plug-in that is part of the JBoss Tools Project for Eclipse. This offers syntax highlighting, indicators for syntax errors, code completion for macro names and bean properties. It must also be noted that the available plug-ins for FreeMarker are not as "strong" as those written for Apache Velocity. Actually, the NetBeans dedicated plug-in doesn"t seem to work for version 7, although online it is indicated that it supports versions greater or equal to 6.

Just as in Apache Velocity"s case, FreeMarker integrates well with Spring MVC. As we have seen in a previous section, Spring MVC offers not only an implementation for ViewResolver but also a library with macros for binding support and form handling.

The project is active, the most recent version 2.3.20 being published on June 2013.

We have seen that the project shows roughly the same advantages like the template processor presented prior to it and we can say also when talking about disadvantages that they are alike. Due to the fact that it has been developed for several years it has become complex, and can seem difficult to master to new users.

Thymeleaf

Thymeleaf is a Java library distributed under the ٢nd version of Apache License with the main goal to create templates in an elegant way. The most suitable use case for Thymeleaf is generation of XHTML / HTML٥ documents within a web context. However this tool can be used in offline environments as well, being able to process XML documents.

Thymeleaf"s creators offer us a module for Spring MVC integration which gives us the possibility to use this product for the visualization layer of our web applications thus being a substitute for JSP. Thymeleaf relies on a set of features called a dialect. The standard distribution comes with the Standard dialect and the SpringStandard dialect which allow us to create so-called natural templates. These can be correctly displayed by the browser even when we access them as static files. Consequently these documents can be viewed as prototypes. If we need other functionalities beside the predefined ones, Thymeleaf allows us to create our own dialects. A dialect offers functionalities such as expressions evaluation or collections iteration.

The Thymeleaf core is built upon a DOM processing engine that is the project"s own high performance implementation. With this mechanism"s help it makes an in-memory representation of the templates and then it performs some processing based on the current configuration and the provided data set, traversing the nodes.

Standard Dialect and SpringStandard Dialect

These two dialects have the same syntax and the main difference between them is the so-called expression language that is being used. While the Standard dialect uses OGNL (Object Graph Navigation Library), the StandardSpring dialect has the Spring Expression Language integrated. Also the SpringStandard dialect contains a series of small adaptations for better using certain functionalities offered by Spring. The syntax used by Thymeleaf in its templates can be noticed in the following example:

Today Software Magazine

When the above template is processed by Thymeleaf it evaluates the expressions figured as values to the attributes located within the th namespace and replaces the values of the classic HTML attributes with the processing result.

For us to benefit from the document"s validation we need to declare the namespace like this:

Spring MVC Integration

As we mentioned earlier Thymeleaf offers us a module for Spring MVC integration, available both for Spring 3 and Spring 4. For us to benefit from this module we added in the pom.xml file of our example the thymeleaf-spring3 dependency from the org.thymeleaf group. The source code of the example project can be downloaded from the following URL: https://springthymeleaf.googlecode.com/svn/trunk.

Advantages and Disadvantages

Thymeleaf is a project that draws in more and more users and also programmers that contribute to its development. The official website offers us a variety of resources that help us get familiar with this product. Moreover the existing documentation teaches us how to extend Thymeleaf with our own dialects. Besides these tutorials we have at our disposal articles on various subjects, a users" forum and an interactive tutorial. Although at the moment of this writing there are no books written about Thymeleaf, we can find many articles about it. Also we can access the thymeleaf and thymeleaf-spring Javadoc API documentation.

This template processor comes with a different philosophy from Velocity and FreeMarker, a thing that can be noticed also in the syntax of the Standard and SpringStandard dialects. Thymeleaf stresses out the concept of natural templating, which offers us the possibility to create static prototypes.

Along with the release of Thymeleaf 2.0 the mechanism for processing the templates was replaced, increasing its performance. Also there is a system for caching the templates.

As far as integration with IDEs is concerned there is a plug-in for Eclipse that offers auto-completion. Unfortunately there is no support for other IDEs.

Similarly to the other projects we talked about the Spring MVC integration is easy to be achieved since the authors of Thymeleaf have created a special module for this task.

The project benefits from frequent releases, the current version being 2.12.RELEASE. This is available to the public since December 2013.

Thymeleaf offers a wide range of functionalities but the tests show that the processing of the templates takes longer than for some of its competitors.

Rythm

Rythm is a template engine for Java applications distributed under the Apache License version 2.0 and described by its author as being a general purpose product, easy to be used and super-fast. Similarly to other template processors, we can process with it HTML documents, XML documents, SQL scripts, source code, emails and any other kind of formatted text. Rythm was inspired by the .Net Razor project, due to its simple and elegant syntax.

Using the same praising words, the author claims that the number one goal of the project is the user experience. From the API to the templates" syntax, the product is characterized by simplicity. Also the product was designed so that it is easy to be used by Java programmers.

The Syntax of the Template Processor

Rythm uses the special character @ to introduce all syntax elements. This thing is illustrated in the following block of code:

@for (product: products) {
  • @product.getName()
  • }

    In order to be able to use Spring MVC model objects within the templates we have to use the following notation:

    @args java.util.List products

    Spring MVC Integration

    For integration with Spring MVC we have at our disposal a third-party library, available as a Maven artifact with the spring-webmvc-rythm id and the com.ctlok group. Having this dependency in our project we can declare the necessary beans in servlet-config.xml. One of rythmConfigurator bean"s properties is mode, with whose help we can specify what mode we are running the application in: dev or prod. The source code of the example application can be downloaded from the following URL: https://springrythm.googlecode.com/svn/trunk.

    Advantages and Disadvantages

    As opposed to Velocity and FreeMarker, Rythm processes the templates transforming them into Java bytecode. Due to this fact at runtime their processing is very fast, placing this project among the fastest template engines of the Java universe.

    Although it"s not as extensive as the documentation of the other products we presented, the documentation of this project is broad, allowing us to acquire the necessary skills for developing web applications using Rythm Template Engine. On the project"s website there is a series of tutorials both for programmers and webmasters and with the help from the dedicated Fiddle instance we can write Rythm templates and visualize the result on the fly. Being a relatively young project, the community around it is not yet developed.

    Rythm is able to operate in two modes: dev (development) and prod (production). Thus in dev mode the templates are reloaded every time when they are modified to shorten the development time; on the other hand in prod mode they are loaded only once to increase performance.

    One of the project"s weak points is the fact that for the moment it doesn"t offer any plug-in for IDEs. Thereby although its syntax is as friendly as it can be, we don"t have assistance from our preferred IDE for writing the templates, an important aspect for many developers.

    Rythm allows us to insert Java code inside templates, but this is one of the aspects that determined us to give up JSP in favor of other template processors. Thus we see this thing as a minus of the project.

    Performances

    There are few tests available that are relevant for determining the performance of the template engines presented in this article, but in the following paragraphs we will show you the results of such studies. Using the benchmarking tool we obtained the following results for 10000 requests:

    • Velocity: 3.8 seconds
    • FreeMarker: 4.8 seconds
    • Thymeleaf: 43.2 seconds
    • Rythm: 3 seconds

    Another test, where Rythm wasn"t included, shows that Velocity and FreeMarker performed almost identically while Thymeleaf was again among the slowest engines.

    Thus Rythm seems to be the fastest template engine among the ones that we talked about in this article, Velocity and FreeMarker strive for second and third place, while Thymeleaf obtained the poorest performance.

    Conclusions

    Although we saw that the projects we presented offer similar functionalities, following this discussion we can draw a few conclusions. Both Velocity and FreeMarker are established products, which proved their worth in many successful projects offering decent performance. On the other hand Thymeleaf and Rythm are young projects that come with a new philosophy adapted to the current trends in web development. For instance, Thymeleaf excels at natural templating, while Rythm offers a clean syntax, easy to understand both for programmers and webmasters. We can conclude that choosing a template engine depends first of all on the project we need it for, every processor we discussed about being worth to be given a try.

    VIDEO: ISSUE 109 LAUNCH EVENT

    Sponsors

    • Accenture
    • BT Code Crafters
    • Accesa
    • Bosch
    • Betfair
    • MHP
    • BoatyardX
    • .msg systems
    • P3 group
    • Ing Hubs
    • Cognizant Softvision
    • Colors in projects

    VIDEO: ISSUE 109 LAUNCH EVENT