FreeMarker Template + Servlet Integration Example

This is my second tutorial about FreeMarker template engine. In my previous tutorial I have explained about how to create stand alone freemarker template. This tutorial explains how to integrate freemarker template to a servlet.

1. Setup FreeMarker Environemnt

It is very simple to setup the freemarker environment by downloading the JAR distribution from its official web page. You can follow my previous tutorial to set up the freemarker project. Only difference is you have to create this project as web project and add the libraries to the lib folder. Once you have created the project, the finel project structure would look like this:

freemarker-project-structure

2. Create a Bean

Create a bean for storing the values.

package javabeat.net.freemarker;
public class Employee {
	private String id;
	private String name;
    private String city;

    public Employee() {
    }

    public Employee(String id, String name, String city) {
        this.id = id;
    	this.name = name;
        this.city = city;

    }
	public String getName() {
		return name;
	}

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

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}

3. Create a Servlet

package javabeat.net.freemarker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
    private List<Employee> employeesList = new ArrayList<Employee>();
    {
    	employeesList.add(new Employee("001", "Rahul", "Bangalore"));
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("employees", employeesList);
        request.getRequestDispatcher("/index.ftl").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String city = request.getParameter("city");
        if(null != name && !name.isEmpty() ) {
           employeesList.add(new Employee(id,name, city));
        }
        doGet(request, response);
    }
}

4. Create FTL Template

FreeMarket template has .ftl extension. It is plain HTML page with the freemarker syntax embeded with the HTML elements. When this page is executed, the values passed from servlets are dynamically inserted to the templates.

<html>
<head><title>FreeMarker Hello World</title>

<body>
  <form name="user" action="hello" method="post">
  	Id: <input type="text" name="id" /> <br/>
    Name: <input type="text" name="name" /> <br/>
    City: <input type="text" name="city" />       <br/>
    <input type="submit" value="Save" />
  </form>

  <table class="datatable">
    <tr>
        <th>ID</th>  <th>Name</th> <th>City</th>
    </tr>
    <#list employees as employee>
    <tr>
        <td>${employee.id}</td> <td>${employee.name}</td><td>${employee.city}</td>
    </tr>
    </#list>
  </table>
</body>
</html>

5. Create Deployment Descriptor For FreeMarker Servlet

We have to configure FreemarkerServlet in the deployment descriptor to detuct the freemarker request. Look at the below entries in the web.xml.

<?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"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

     id="WebApp_ID" version="2.5">
     <display-name>FreeMarker Servlet Example</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>freemarker</servlet-name>
        <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
        <!-- FreemarkerServlet settings: -->
        <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; charset=UTF-8</param-value>
            <!-- Forces UTF-8 output encoding! -->
        </init-param>
        <!-- FreeMarker settings: -->
        <init-param>
            <param-name>template_update_delay</param-name>
            <param-value>0</param-value>
            <!-- 0 is for development only! Use higher value otherwise. -->
        </init-param>
        <init-param>
            <param-name>default_encoding</param-name>
            <param-value>ISO-8859-1</param-value>
            <!-- The encoding of the template files. -->
        </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>
    <servlet>
        <servlet-name>FreeMarketServletExample</servlet-name>
        <servlet-class>javabeat.net.freemarker.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FreeMarketServletExample</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

6. Run The Application

If you run the above example, you would see the below screen as output.

freemarker-servlet

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*