Saturday, January 3, 2009

Tiles 2, a cheaper configuration

In a previous post I described how to use Tiles 2 in a Parancoe/Spring MVC project. What is really irritating for me in Tiles is its configuration file, a long list of almost identical XML fragments. Moreover that configuration rarely needs to be changed, so it's in practice useless, and just a waste of time (and effort) during the development.

If your application, as usually, has a main layout, and only few pages adopt a specific layout, I think there could be an easy and pleasant solution.

I defined a new view class (CheapTilesView) that can be used with an UrlBasedViewResolver:

<bean id="viewResolver"
<property name="viewClass" value="org.parancoe.plugin.tiles.CheapTilesView"/>

Now the Tiles configuration file could be simply:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
<definition name="template.main" template="/WEB-INF/tiles/templates/main.jsp">
<put-attribute name="header" value="/WEB-INF/jsp/header.jsp"/>
<put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp"/>
<put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp"/>

(compare with the configuration of the previous post)

All the omitted definitions are automatically created at runtime using the URL. For example, if the URL is admin/conf and a definition with that name doesn't already exist in your configuration file, the CheapTilesView class will generate (at runtime) this for you:

<definition name="admin/conf" extends="template.main">
<put-attribute name="main" value="/WEB-INF/jsp/admin/conf.jsp"/>

So in you configuration file you only need to write the definitions of your (usually few) pages with a specific layout.

The conventions used by the CheapTilesView can be customized passing some attributes to the view resolver. The following are the default values:

<bean id="viewResolver"
<property name="viewClass" value="org.parancoe.plugin.tiles.CheapTilesView"/>
<property name="attributesMap">
<entry key="org.parancoe.plugin.tiles.CheapTilesView.DEFAULT_TEMPLATE" value="template.main"/>
<entry key="org.parancoe.plugin.tiles.CheapTilesView.DEFAULT_ATTRIBUTES" value="main"/>
<entry key="org.parancoe.plugin.tiles.CheapTilesView.DEFAULT_PREFIX" value="/WEB-INF/jsp/"/>
<entry key="org.parancoe.plugin.tiles.CheapTilesView.DEFAULT_SUFFIX" value=".jsp"/>

The class is available in the Parancoe svn repository. Very soon it will be released as a Parancoe plugin. Stay tuned.


Subtitle said...

Very clever! But, now Tiles 2.2 provides wildcards and regular expression definitions.

Lucio Benfante said...

@Subtitle: thank you. I will try it.

Ravi said...

Really, Tiles gives good look to your home. To purchase a particular type of tile, it is better to go to the wholesale tiles distributors, who deals with those tiles wholesale. This way you will be able to save quite a handful of money.