Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

9.14. Using FreeMarker in a Web Application

9.14.1. Problem

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

9.14.2. 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>

9.14.3. 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 by assigning a reference to JspTaglibs["/WEB-INF/app-taglib.tld"] in an <#assign> directive. The tag can then be used with a call to <@app.printStuff/>:

<#assign app=JspTaglibs["/WEB-INF/app-taglib.tld"]>
<p>
 This is an HTML page with a taglib in it.
</p>
<@app.printStuff var="test" mode="fast"/>

That couldn't be much simpler.

9.14.4. See Also

This is a valuable piece of functionality if you are using a framework like Struts, which depends on JSP tag libraries. For more details about using FreeMarker with Struts, see "Using FreeMarker with Servlets" (http://fmpp.sourceforge.net/freemarker/pgui_misc_servlet.html).


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.