In this
post I will show you how to configure and start coding views with Spring MVC
and Apache Tiles. By default Spring don’t give us any rich user interface
library and template engine, actually why it should? It doesn’t have to.
The second
one is a must have element in every web application. Spring have possibility to
integrate with few template engines like Velocity, FreeMaker or Apache Tiles. I
will show you how to use the last one.
Let’s do it…
1. Configure viewResolver
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
2. Create tiles definitions
<!DOCTYPE tiles-definitions
PUBLIC
"-//Apache Software Foundation//DTD Tiles
Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="myTemplate"
template="/views/templates/myTemplate.jsp">
<put-attribute name="body"
value="" />
<put-attribute name="header"
value="/views/templates/header.jsp" />
<put-attribute name="footer"
value="/views/templates/footer.jsp" />
</definition>
<definition name="index"
extends="myTemplate">
<put-attribute name="body"
value="/views/templates/blank.jsp" />
</definition>
</tiles-definitions>
3. Create template
<html>
<head>
<title>My app</title>
</head>
<body>
<div class="container">
<tiles:insertAttribute name="header"
/>
<div id="body-class"
class="banner">
<tiles:insertAttribute name="body"
/>
</div>
</div>
<br />
<div>
<div class="container"
style="padding-top: 50px;">
<tiles:insertAttribute name="footer"
/>
</div>
</div>
</body>
</html>
References: