9.14. Using FreeMarker in a Web Application

Problem

You would like to use FreeMarker templates in a web application.

Solution

FreeMarker ships with a FreemarkerServlet, which can be configured to render your FreeMarker templates. To configure this servlet, add the following servlet and servlet-mapping elements to your web.xml file:

<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</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>

Discussion

If your application contains custom JSP tag libraries, these tag libraries can be used from a FreeMarker template. To see how a JSP tag library can be used in FreeMarker, take a look at the following JSP page, which references an app tag library with a TLD file in /WEB-INF/app-taglib.tld:

<%@page language="java"%>
<%@taglib uri="/WEB-INF/app-taglib.tld" prefix="app"%>

<p>
 This is an HTML page with a taglib in it.
</p>

<app:printStuff var="test" mode="fast"/>

The app tag library has a printStuff tag, which takes the parameters var and mode. The same tag can be used in a FreeMarker template ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.