Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Saturday, July 8, 2023

Apach FreeMarker HelloWorld Tutorial and Example in Java

Apache FreeMarker is a free, open source, Java based template engine which allow you to create dynamic content by combining the static template with dynamic data. The template is written in their own proprietary language called FTL(FreeMarker Template language), which is like any scripting language which allows you to insert variables, looping constructs and conditional logic. FreeMarker is often used with JSP in MVC based Java application to generate dynamic content but it's not limited to Servlet or JSP and you can use with core Java as well. In fact, this FreeMarker Hello World Example is without JSP. We generate a dynamic HTML file by using Freemarker in the main() method itself. Apache FreeMarker is often used for generating source code, configuration files or personalised e-mails.


Tools used in this Example

1. Java

2. Eclipse

3. FreeMarker


Project Dependencies

This is a FreeMarker hello world program and it only needs freemarker JAR and its dependencies. If you are using Maven, you can just add following dependency in your pom.xml file, this will not only download freemarker JAR but also all the dependent JAR freemarker needs.

<dependencies>
	<dependency>
		<groupId>freemarker</groupId>
		<artifactId>freemarker</artifactId>
		<version>2.3.9</version>
	</dependency>
</dependencies>

Alternatively, if you are not using Maven, you can add following JAR files manually in your Java program's classpath. If you are not sure how to set classpath in Eclipse, checkout here.

.m2\org\freemarker\freemarker\2.3.9\freemarker-2.3.9.jar

Apach FreeMarker HelloWorld Tutorial and Example in Java



FreeMarker HelloWorld Example

In order to create hello world in freemarker, you need two things, first a freemarker template and second a data model. You also need a Java class to combine template and data model, but your Java class can also provide data model in terms of objects. Alternatively, you can use XML file to provide data. 

freemarker.ftl

This is the freemarker template file. It must be in your Java program's classpath to be picked up by the program which is using freemarker.

<html>
	<head>
		<title>Welcome! to FreeMarker HelloWorld Example</title>
	</head>
	<body>
		<h1>Welcome ${user}!</h1>
		<p>Our latest course : ${latestCourse.name}
                     with price is ${latestCourse.price}</p>
	</body>
</html>

You can see that template is generating an HTML file with user and course coming as dynamic content. This data will come from data model, which is a HashMap in our hello world tutorial, but it could be an XML file as well in real world.


How freemarker works



Course.java

This is a Java bean, hence it must be public. This class is part of our data model, FreeMarker will extract latestCourse.name and latestCourse.price value from this class, hence this class should have a name and price attribute and corresponding public getter methods.


/**
* Course bean, it must be a public class
*/

public class Course {
    private String name;
    private long price;

    public Course(String name, long price) {
        this.name = name;
        this.price = price;

    }


    public String getName() {
        return name;
    }



    public long getPrice() {
        return price;
    }

    public void setName(String name) {
        this.name = name;
    }


    public void setPrice(long price) {
        this.price = price;
    }
}

Make sure this class is public otherwise your FreeMarker Hello World program will not run and give following error:

Exception in thread "main" 

Expression latestCourse.name is undefined on line 7, column 28 in freemarker.ftl.

The problematic instruction:

----------

==> ${latestCourse.name} [on line 7, column 26 in freemarker.ftl]

----------


Java backtrace for programmers:

----------

freemarker.core.InvalidReferenceException: Expression latestCourse.name is undefined on line 7, column 28 in freemarker.ftl.

at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124)

at freemarker.core.Expression.getStringValue(Expression.java:118)

at freemarker.core.Expression.getStringValue(Expression.java:93)

at freemarker.core.DollarVariable.accept(DollarVariable.java:76)

at freemarker.core.Environment.visit(Environment.java:196)

at freemarker.core.MixedContent.accept(MixedContent.java:92)

at freemarker.core.Environment.visit(Environment.java:196)

at freemarker.core.Environment.process(Environment.java:176)

at freemarker.template.Template.process(Template.java:232)

at FreeMarkerHelloWorld.main(FreeMarkerHelloWorld.java:37)


to avoid this error just make sure that your Course class is public


FreeMarkerHelloWorld.java

This is the main class which will drive the program. It is responsible for creating freeMarker configuration and combining freemarker template with data model. In this tutorial, we have provided data in HashMap, you can see its key is the variable name used in the template file and values are the text which should replace those variables.


In real world you can populate this Map with an XML file or from database.

import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;



/**
* A Freemarker hello world tutorial. Freemarker is a Java based templating
* engine which allow you to merge static text with dynamic content e.g.
* creating personalized emails and messages.
* 
* @author javin paul
* 
*/

public class FreeMarkerHelloWorld {

    public static void main(String...args) throws Exception {

        // create configuration, only once in application
        Configuration cfg = new Configuration();

        // creating a data model
        // key is variable name in template
        // value is the text which would replace the variable

        Map < String, Object > model = new HashMap < String, Object > ();
        model.put("user", "John");
        model.put("latestCourse", 
                   new Course("FreeMarker Beginner Course",
                             100));

        // get the template
        Template t = cfg.getTemplate("freemarker.ftl");


        // combine data model with template
        Writer out = new OutputStreamWriter(System.out);

        t.process(model, out);

        System.out.println("Done..");

    }

}


When you run this program, you will get following output

<html>
	<head>
		<title>Welcome! to FreeMarker HelloWorld Example</title>
	</head>
	<body>
		<h1>Welcome John!</h1>
		<p>Our latest course : FreeMarker Beginner Course 
                     with price is 100</p>
	</body>
</html>Done..


In our example, I have printed the output in console but you can also write output into an HTML file by using a FileWriter object as explained here. 


That's all about freemarker hello world example in Java. As I told you can use this library to create dynamic content even on core Java project but it mostly used along with JSP in MVC projects. I have used this technology in one of the important Java project in past where we display a lot of static and dynamic data using Apache FreeMarker. 


No comments :

Post a Comment