Using FreeMarker in a JSP taglib

Simple steps to create a JSP taglib which (internally) uses the FreeMarker engine for generating the output .

The JSP taglib is responsible for defining the name, attributes and behavior of the tag whilst the generation of the output (i.e. html code, predefined text template) is delegated to the FreeMarker engine.

This technique brings various advantages such as the separation of responsibilities (“presentation-designer” vs “business-programmer”), better maintenance and extendibility.

The approach is similar to the Struts2 JSP tags: this is just a simpler implementation to see what happens behind the scene.

Create the JSP taglib

The JSP tag can be defined extending the SimpleTagSupport and overriding the doTag() method.

Attributes are defined as private variables with associated setters (getters are not strictly necessary).

The custom tag is free to implement any specific logic, from simple pre-processing of data to sophisticated business rules and even database access… (never, please, never! :shock:).

When it is time to delegate to the FreeMarker template the steps are pretty simple:

  • initialise a Configuration object
  • load the template
  • process the template and stream the output

Initialise the FreeMarker engine

The “freemarker.template.Configuration” object is the core of the FreeMarker engine. Amongst various settings it allows the client applications to set how the templates are loaded.

Three built-in loaders are provided:

  • file system loader (setDirectoryForTemplateLoading()): templates are available in a directory of the file sytem
  • class loader (setClassForTemplateLoading()): templates are loaded from the class path
  • servlet context (setServletContextForTemplateLoading()): templates are loaded from the root of the web application

Each template might suit different scenario, in my example however I used the ClassPath loader as it gives the flexibility to store the ftl files within the same jar as the JSP taglib.

  Configuration configuration = new Configuration();
  // set a default implementation of the ObjectWrapper (data interactions)
  configuration.setObjectWrapper(new DefaultObjectWrapper());
  configuration.setClassForTemplateLoading(Engine.class,
        "/template/default/");

Load a given template

Via the Configuration object the template is then loaded by name:

  Template template = configuration.getTemplate("picklist.ftl");

The piciklist.ftl is found in the “/template/default” in the jar file.

Output generation: process of the template

Before the actual streaming there in facts another (very important) step: merging the template with the data model (information made available to the tempate).

The data model is defined from within the Java code, then merged with the template:

  /* Create a data-model */
  Map data = new HashMap();
  data.put("attributeOne", attributeOne);
  data.put("attributeTwo", attributeTwo);
  /* Merge data-model with template */
  PageContext pageContext = (PageContext) getJspContext();
  JspWriter out = pageContext.getOut();
  template.process(data, out);

Create the FreeMarker template

The FreeMarker template is a text file which resides somewhere in the JAR file.

Within the ftl file you will find text, html, css, anything you like blended with the FreeMarker language. The data model passed from the JSP tag (HashMap) is used to generate the output.

  <html><body>
  Value of AttributeOne is ${attributeOne}
  Value of AttributeTwo is ${attributeTwo}
  </body></html>

Ready to go

Embed the taglib in your JSP and use it according to the provided TLD file:

  <%@ taglib uri="/ftl-tags" prefix="my-ftl" %>
   ...
  <my-ftl:tagOne attributeOne="Ciao" attributeTwo="Grazie" />

Conclusion

Using JSP and FreeMarker together is an effective technique for building presentation-oriented JSP taglib. As the presentation code stays within the FreeMarker template, the Java developers can focus on the pre-processing of the information and definition of the data model whilst skilled designers – not me :mrgreen: – generates astonishing UI.

Another interesting aspect is the possibility to define multiple skins/themes for the same tag: in this case, based on the user preferences or environment settings (intranet vs web site), different templates can be loaded and different GUI can be generated.

Download the sample project here.

Advertisements

2 Responses to Using FreeMarker in a JSP taglib

  1. Beppe says:

    Pls see the sample project, hope it helps

    Ciao
    Beppe

  2. vijay pandey says:

    can any one provide any real examples

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: