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