Monday, October 27, 2008

Tiles2 with Spring without Spring MVC

In the process of making my application OSGI enabled, I came to the conclusion that it would help me better to have Tiles2 to be managed by Spring. This is so as to have more control of the Tiles2 configuration instead of the configuration needed in web.xml. This is when I found the TilesConfigurer class from Spring. Here is a snippet of for my configuration.

Now, this means that web.xml no longer needs the Tiles2 listener but simply let Spring's Servlet configuration do the initializing for you. If you are using Spring MVC, this is already done, if you are not, you may need to use RequestContextListener or the ContextLoaderListener so that this tilesConfigurer bean is placed in application scope similar to what the Tiles2 configurer does out of the box.

Warning: leaving the Tiles2 listener (along with the configuration above) will still try to load the tiles.xml from the default location (WEB-INF folder) so you may be overriding the work already done by Spring's SpringBeanPreparerFactory. Take a look at the generated logs for further detail. Once you have this, now you have control (in Spring) over Tiles2. I wanted to add a custom TilesDefinitionsFactory so I created my own as follows:
package myPackage.MyTileDefinitionsFactory;

public class MyTileDefinitionsFactory extends UrlDefinitionsFactory {
  public Definition getDefinition(String name, 
                     TilesRequestContext ctx)
    throws DefinitionsFactoryException {
    Definition tileDefinition = super.getDefinition(name, ctx);

    // add you own logic to modify/update template and/or tile

    return tileDefinition;
With this new factory, now we were able to introduce custom menus, tabs, and other widgets to screens based on roles and/or other business ruls (e.g. workflows). Furthermore, we were even able to change the backing template (eventhough the Tiles2 documentation says you can not change the template of a tile dynamically, this did the trick). There are many other possibilities opened with this approach that I'm sure some will find useful.

One more thing to keep in mind, you need to setup the property useMutableTilesContainer to true so as to be able to great dynamic tiles. As you read the Tiles API, you can potentially create your own tiles dynamically as well as simply modify existing ones. I found this approach to be a very powerful one when integrating Tiles2 with Struts2.

Hope this helps!

No comments: