Using Tiles in Spring MVC
by, 11-27-2011 at 11:39 PM (4921 Views)
In earlier tips, I talked about using Spring MVC and the use of different view technologies. In this tip, I will look at Tiles as a view technology for Spring MVC. Tiles was initially built to be used with the Struts Framework. But as it is a powerful view technology it has been reused by other web frameworks. To use Tiles with Spring MVC you need to register the Tilesí view resolver as a bean with the applicationís xml file, springexamples.xml.
This view resolver that will attempt to find views that are defined as Tiles templates . The logical view name is exactly the same as the Tiles definition name. The TilesViewResolver relies on TilesConfigurer to keep track of that information. So the bean definition fo the TilesConfigurer would be the following:Java Code:<bean class= "org.springframework.web.servlet.view.tiles2.TilesViewResolver"/>
TilesViewResolver will leverage the TilesConfigurer to load one or more Tiles definition files in order to resolve the views. For the Springexamples application there are a few Tiles definition files, all named views.xml, under the /WEB- INF/views folder. You then wire /WEB-INF/views/**/views.xml into the definitions property. By using the Ant-style ** patterns, the entire directory hierarchy under /WEB-INF/views will be searched for files named views.xml. The definition is shown below:Java Code:<bean class= "org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/viewsviews.xml</value> </list> </property> </bean>
The home template will be found by the TilesViewResolver when it tries to resolve the logical view name returned by HomeControllerís showHomePage() methods. The home definition extends the template definition. It uses the home.jsp to render the main content on the page by incorporating all the common features of the page. DispatcherServlet will send the request to Tiles to render the results using the home definition. In the next tip, I will show you how to render the home page view with tiles.Java Code:<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN" "http://tiles.apache.org/dtds/tiles-config_2_1.dtd"> <tiles-definitions> <definition name="template" template="/WEB-INF/views/main_template.jsp"> <put-attribute name="top" value="/WEB-INF/views/tiles/carForm.jsp" /> <put-attribute name="side" value="/WEB-INF/views/tiles/login.jsp" /> </definition> <definition name="home" extends="template"> <put-attribute name="content" value="/WEB-INF/views/home.jsp" /> </definition> </tiles-definitions>