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:
To use Apache FreeMarker, we need to add its dependency:
1 2 3 4 5 |
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.27-incubating</version> </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:
with the following content:
1 |
Hello ${name} |
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.
The contents of the Application class are as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.huongdanjava.freemarker; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class Application { public static void main(String[] args) { Configuration configuration = new Configuration(Configuration.VERSION_2_3_27); configuration.setClassForTemplateLoading(Application.class, "/"); try { Template template = configuration.getTemplate("hello.ftl"); StringWriter writer = new StringWriter(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "Khanh"); template.process(map, writer); System.out.println(writer); } catch (Exception e) { e.printStackTrace(); } } } |
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: