Freemarker: Java based template engine

0
388

Freemarker is a Java based template engine that can be used both in stand-alone mode and in a Web environment, it provides a Template file that contains the output to display associated with the place-holders regarding any parts that we want to provide dynamically.

<pre class=”brush: php; html-script: true”>
<Html>
<Body>
<H1> $ {title} </ h1>
</ Body>
</ Html>
</pre>

In the example it ${title}indicates a variable that will be supplied to the template in a dynamic way. This will be done by Java, in fact it will be Freemarker that will allow the template to provide dynamic values to be displayed. This mode allows a decoupling between the View and the back-end part, this is because those who create the template may not know what it represents ${title}but, more simply, expect that the value is provided at runtime.

Installation

We download the Freemarker library from the download section that we find at http://freemarker.org/freemarkerdownload.html and store it in a separate directory, we will use it later:

Freemarker library download
Freemarker library download

Now we open Eclipse, in our case we have used Kepler , and install the plugin for Freemarker selecting in eclipse the voice “help / Install New Software” and, by entering the url http://download.jboss.org/jbosstools/updates/stable/kepler/, select the Freemarker IDE for both checkboxes as shown:

Choice of the freemarker IDE for Eclipse
Choice of the freemarker IDE for Eclipse

A prime example of use in Eclipse

In Eclipse we create a Java project, called for example “FreemarkerProject”, and the template mytemplate.ftlunder the folder templates:

The template file.
The template file.

We therefore create the following Bean:

package com.freemarker; public class Developer {
private String name;
private String project;
    public Developer (String name, String project) {
        this.name = name;
        this.project = project;
    }

    public String getName () {
        return name;
    }

    public String getProject() {
        return project;
    }
}

As names, the two fields of the Bean have “name” and “project”, we will see later how this is not a case. We now create a test class that will load the template and bind the values with those that the template expects to receive:

package com.freemarker.test; 

.. imports 

public class TestOutput {

public static void main(String[] args) {
    // configuration object of Freemarker
    Configuration cfg = new Configuration();

    // definiamo la classe che carica il template
    cfg.setClassForTemplateLoading(TestOutput.class, "templates");

    // recommended settings
    cfg.setIncompatibleImprovements(new Version(2, 3, 20));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setLocale(Locale.US);
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    // the layout of the template
    try {
    // absolute path to the template
        cfg.setDirectoryForTemplateLoading(new File("C:/Users/g.astarita/Desktop/Work/WS Articoli/FreemarkerProject/templates"));

        // data model generation
        Map<string, object=""> data = new HashMap&lt;string, object="">();
        String title = "Freemaker example";
        data.put("title", title);
        Developer developer = new Developer("giuseppe","Progetto Telecom");
        data.put("developer", developer);

        Template template = cfg.getTemplate("mytemplate.ftl");

        // Console output
        Writer out = new OutputStreamWriter(System.out);
        template.process(data, out);
        out.flush();

        // File output
        Writer file = new FileWriter (new File("freemarkerOutput.txt"));
        template.process(data, file);
        file.flush();
        file.close();
        } catch (IOException e) {       
            e.printStackTrace();
        } catch (TemplateException e) {
             e.printStackTrace();
    }

}

}
</string,></string,>

The functionality of this class is to load the template and to bind; in the Hashmap datawe insert first the string “title”, done this the code will create a Bean with two fields, developer.nameand developer.project, just the two remaining variables that the template expects. Finally, the code will write the output on console and in a file:

The result on console
The result on console

A more complex example: a Web application

Now, let’s create the Dynamic Web Project FreemarkerWebProject and, to do this, open the file Web.xmland add the part related to the configuration:

<pre class=”brush: php; html-script: true”>
<? xml version = “1.0” encoding = “UTF-8”?>
<Web-app xmlns: xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://Java.sun.com/xml/ns/Javaee”
xsi: schemaLocation = “http://Java.sun.com/xml/ns/Javaee http://Java.sun.com/xml/ns/Javaee/Web-app_3_0.xsd” id = “WebApp_ID” version = ” 3.0 “>
<Display-name> FreemarkerWebProject </ display-name>
<Servlet>
<Servlet-name> freemarker </ servlet-name>
<Servlet-class> freemarker.ext.servlet.FreemarkerServlet </ servlet-class>
<Init-param>
<Param-name> TemplatePath </ param-name>
<Param-value> / </ param-value>
</ Init-param>
<Init-param>
<Param-name> NoCache </ param-name>
<Param-value> true </ param-value>
</ Init-param>
<Init-param>
<Param-name> ContentType </ param-name>
<Param-value> text / html; </font><font style=”vertical-align: inherit;”>charset = UTF-8 </ param-value>
</ Init-param>
<Init-param>
<Param-name> template_update_delay </ param-name>
<Param-value> 0 </ param-value>
</ Init-param>
<Init-param>
<Param-name> default_encoding </ param-name>
<Param-value> ISO-8859-1 </ param-value>
</ Init-param>
<Init-param>
<Param-name> number_format </ param-name>
<Param-value> 0. ########## </ param-value>
</ Init-param>
<Load-on-startup> 1 </ load-on-startup>
</ Servlet>
<Servlet-mapping>
<Servlet-name> freemarker </ servlet-name>
<Url-pattern> *. Ftl </ url-pattern>
</ Servlet-mapping>
<Welcome-file-list>
<Welcome-file> index.html </ welcome-file>
<Welcome-file> index.htm </ welcome-file>
<Welcome-file> index.jsp </ welcome-file>
<Welcome-file> default.html </ welcome-file>
<Welcome-file> default.htm </ welcome-file>
<Welcome-file> default.jsp </ welcome-file>
</ Welcome-file-list>
</ Web-app>
</pre>

In this way a Freemarker servletDispatcher will be loaded which will filter the RL requests and manage those ending for “.ftl” interpreting them as a request to the engine, thus allowing the dynamic merging between parameters and template. After creating the Web project, we will have to perform the following steps:

The Web project
The Web project

So, in order, we have:

  1. reused the Developer bean;
  2. added the libraries for the compilation;
  3. created our template file under the folder WebContent.

Now let’s create the following servlet under the package com.myservlet:

package com.myservlet;
import Java.io.IOException;
  import Java.io.PrintWriter;
  import Java.util.ArrayList;
  import Java.util.HashMap;
  import Javax.servlet.ServletException;
  import Javax.servlet.annotation.WebServlet;
  import Javax.servlet.http.HttpServlet;
  import Javax.servlet.http.HttpServletRequest;
  import Javax.servlet.http.HttpServletResponse;
import com.freemarker.Developer;
 
  @WebServlet ( "/ HelloServlet")
  public class HelloServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
 
  public HelloServlet () {
  
  }
 
  protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // let's create the list of developers
  ArrayList &lt;Developer&gt; developers = new ArrayList &lt;Developer&gt; ();
  developers.add (new Developer ("Claudio", "Html.it"));
  developers.add (new Developer ("Alfredo", "Html.it"));
  developers.add (new Developer ("Giuseppe", "Engineering"));
  
  // set the list as a parameter of the request
  request.setAttribute ("developers", developers);
  
  // binding the list with the template
  request.getRequestDispatcher ("/ mytemplate.ftl"). forward (request, response);
  
  }
}

This, finally, our template mytemplate.ftl:

<pre class=”brush: php; html-script: true”>
<Html>
<head> <title> Freemarker Web Example </ title>
<Body>
<Table>
<Tr>
<th> Firstname </ th> <th> Lastname </ th>
</ Tr>
<#list developers as developer>
<Tr>
<td> $ {developer.name} </ td> <td> $ {developer.project} </ td>
</ Tr>
</ # List>
</ Table>
</ Body>
</ Html>
</pre>

We deploy the Web appliction on a target server and load the URL of our servlet:

The output of the servlet.
The output of the servlet.

In this case the template script has retrieved the list of beans and for each has printed the fields on video through the Freemarker constructs.

An important consideration is that we can edit the template ftlas if it were an HTML page, so with all the tools that a modern Web editor offers; but to get this we will have to treat the template as HTML page and rename it with extension ftl:

The Eclipse Web editor with the template in HTML format
The Eclipse Web editor with the template in HTML format

LEAVE A REPLY

Please enter your comment!
Please enter your name here