View Preparers

Sometimes a definition, before it is rendered, needs to be "prepared". For example when showing a menu, the menu structure must be created and stored in the request scope.

For this reason, a View Preparer can be used: it is called before the definition is rendered, so all the things needed to render correctly the definition can be prepared.

Creating a view preparer

A View Preparer is simply a class that implement the ViewPreparer interface. The execute method allows to execute code before a definition is rendered. You can extend the ViewPreparerSupport class to avoid compiling problems in the case the ViewPreparer interface changes.

package my.package;

import org.apache.tiles.preparer.PreparerException;
import org.apache.tiles.preparer.ViewPreparer;
import org.apache.tiles.context.TilesRequestContext;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.Attribute;

public class TestViewPreparer implements ViewPreparer {

    public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext)
    throws PreparerException {
        attributeContext.putAttribute(
            "body",
            new Attribute("This is the value added by the ViewPreparer"));
    }
}

Associating a preparer

To associate a preparer to a definition, put its complete path name to the preparer attribute of the <definition> element:

<definition name="preparer.definition" preparer="org.apache.tiles.test.preparer.TestViewPreparer">
  <put-attribute name="foo" value="/bar/foo.jsp" />
</definition>  

Customizing View Preparer association

Currently the preparer is associated to a definition using its class name. There will be only one instance per unique class name. If you want to customize this behaviour, you have to create your own implementation of the PreparerFactory interface.

For example, the Struts 1 - Tiles 2 integration defines a PreparerFactory that can use a URL as a preparer.