Hello World with FreeMarker

Apache FreeMarker is a template engine, a Java library for generating output based on available data input and templates. In this tutorial, I will guide you to a simple example with Apache FreeMarker to have a basic overview about it.

First, I will create a Maven project as an example:

Hello World with FreeMarker

To use Apache FreeMarker, we need to add its dependency:

To work with Apache FreeMarker, as it is a template engine, the first thing we need is a template file. The contents of this file must be written using the FreeMarker Template Language (FTL) of Apache FreeMarker. We need to create a template file .ftl and define the placeholders in this file. The placeholder will be words starting with the $ character and then the property name enclosed by opening and closing curly brackets, such as ${name}.

In this example, we will create a hello.ftl file located in the /src/main/resources directory:

Hello World with FreeMarker

with the following content:

During processing, Apache FreeMarker will replace the placeholder ${name} with the value of the name attribute that we passed.

Now let’s create an application class to run the example.

Hello World with FreeMarker

The contents of the Application class are as follows:

In the above code, I created a new Apache FreeMarker Configuration object with version 2.3.27. This Configuration object is the central object containing the configuration of Apache FreeMarker in our application. We will point to the location that will load the .ftl template file using this Configuration object.

To load the contents of the template file, we will use the Apache FreeMarker Template object. By using the process() method of the Template object with the input of a Map object containing key and value information, we can generate the output which we want.

Result:

Hello World with FreeMarker

 

Add Comment