You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to auto generated source code) based on templates.

Configure your action to use the "freemarker" result type

The "freemarker" result type is defined in struts-default.xml. To create pages using FreeMarker, set the result type of the actions to "freemarker".

<include file="struts-default.xml"/>
...
<action name="test" class="package.Test">
  <result name="success" type="freemarker">/WEB-INF/views/testView.ftl</result>
</action>
...

Using properties

FreeMarker uses the ${...} notation to access properties. They are called interpolations. Properties on the actions (getter methods) will automatically be available on the FreeMarker templates. If an action has a "getName()" method, then its value can be inserted on the template like:

Your name is: ${name}

Property resolution

When a property is referenced in a FreeMarker template, the following scopes will be searched in order, until a value is found:

  1. variables defined on the template
  2. value stack (Action properties will be found on this step)
  3. request attributes
  4. session attributes
  5. servlet context attributes

If a property is defined on the template with the same name as a property on the action, FreeMarker will use the property defined locally, on the template.

Be Careful

By default, FreeMarker will throw an error if it finds a variable that is not defined, or has a null value. See this FAQ for details.

Provided objects

The following variables are provided by Struts to the FreeMarker templates:

  • req - the current HttpServletRequest
  • res - the current HttpServletResponse
  • stack - the current OgnlValueStack
  • ognl - the OgnlTool instance
    • This class contains useful methods to execute OGNL expressions against arbitrary objects, and a method to generate a select list using the <s:select> pattern. (i.e. taking the name of the list property, a listKey and listValue)
  • struts - an instance of StrutsBeanWrapper
  • action - the current Struts action
  • exception - optional the Exception instance, if the view is a JSP exception or Servlet exception view

FreeMarker configuration

To configure the FreeMarker engine, just add a file freemarker.properties to the classpath. The supported properties are those that the FreeMarker Configuration object expects, see FreeMarker's documentation for more details.

freemarker.properties
default_encoding=ISO-8859-1
template_update_delay=5
locale=no_NO
  • No labels