Welcome to TechYari!

Tutorials on webdesign, web development and more...

Spring 4 MVC and Apache Tiles 3 Integration Tutotial Using Annotation Based Configuration

By  TechYari     6/04/2015    Labels:,, 
In this post we are going to look at Apache Tiles 3 integration with Spring MVC. Apache Tile is one of the oldest template system used in Java based web application. We will use Spring MVC's annotation based configuration to integrate Apache Tiles 3 with Spring MVC. I ahve also used bootstrap in the main JSP file to make it look better. You can download the source code and try it yourself.


  1. Java Development Kit (JDK) 1.7 or higher
  2. Spring Source Tool Suite (STS) or Eclipse with Maven and STS Plugin
  3. Maven 3 or higher
  4. Deafult STS server (Pivotal tc server) / Apache Tomcat 7 or higher
  5. Working internet connection (for maven to download dependencies)

Setting Up Development Environment

If you don't have development environment setup, you can check my previous tutorial ( ) for setting up development environment using all the tools mentioned above.

Create a new Spring MVC project using Maven

Open your STS/Eclipse and create a new Maven Project. Check create a simple project (skip archtype selection) checkbox. Refer below screenshot for next step:

Adding required dependiencies fro Spring MVC and Apache Tiles

Next step is to add required dependencies for Spring MVC and Apache Tiles, as we need the jar's to start our integration. Add following dependencies to your POM.xml file. Refer below code for example
<project xmlns="" xmlns:xsi=""





Creating Packages and Folder Structure

Now create three new packages inside src folder-
  • in.techyari.smat.config
  • in.techyari.smat.controller
  • in.techyari.smat.model
Also create following folder structure to hold JSP files-
Create following folders inside WebContent folder. first create WEB-INF/views/jsp, and then three more folder inside jsp i.e. layouts, templates and tiles. You can refer the screenshot below to understand more..

Configuring Spring MVC with Annotations Based configuration

We will use Java code to configure Spring MVC instead of web.xml file, create a new class namedApplicationInitializer inside in.techyari.smat.config folder, ignore the error with MyAppConfig for now, we will create that class later. Refer below code:
package in.techyari.smat.config;


public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {

    protected Class<?>[] getRootConfigClasses() {
        return null;

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MyAppConfig.class};

    protected String[] getServletMappings() {
        return new String[]{"/"};

Creating Our Main Layout for Apache Tiles

Next step is to create the layout we want to use for displaying content. We will create a basic jsp page inside layouts folder with header, body and footer area which will be filled by Spring MVC using Apache Tiles. for example jsp <tiles:insertAttribute name="header" /> in below code will be replaced by actual header content. I have used bootstrap for styling CSS. Refer code block below:
<%@ taglib uri="" prefix="tiles" %>
<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title><tiles:getAsString name="title"/></title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="">
    <style type="text/css">{padding:15px 10px;},{color:white;}
    <div class="container">
        <div class="row">
            <div class="col-md-12" id="header">
                <tiles:insertAttribute name="header" />
        <div class="row">
            <div id="body">
                <tiles:insertAttribute name="body" />
            <div class="row">
            <div class="col-md-12" id="footer" style="margin-top:200px;border-top:1px solid gray">
                <tiles:insertAttribute name="footer" />


Creating Apache Tiles Definations

Now we need to create definations for our pages, since this is just a tutorial lets have two pages, a Home page and a Products page. We will create a defination for both of them using tiles.xml and products.xml. Create these tiles inside tiles folder.
tiles.xml (used for home page)
Don't worry about the jsp files mentioned here,we will create them later, important thing to see here is how we map the String value for title and the templates for header,body and footer.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
  <definition name="myapp.homepage" template="/WEB-INF/views/jsp/layouts/main.jsp">
    <put-attribute name="title" value="Spring MVC Tiles Integration" />
    <put-attribute name="header" type="template" value="/WEB-INF/views/jsp/templates/header.jsp" />
    <put-attribute name="body" type="template" value="/WEB-INF/views/jsp/templates/welcome.jsp" />
    <put-attribute name="footer" type="template" value="/WEB-INF/views/jsp/templates/footer.jsp" />


Similarly we create products.xml and map it's body to products.jsp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
  <definition name="myapp.products" template="/WEB-INF/views/jsp/layouts/main.jsp">
    <put-attribute name="title" value="Spring MVC Tiles Integration" />
    <put-attribute name="header" type="template" value="/WEB-INF/views/jsp/templates/header.jsp" />
    <put-attribute name="body" type="template" value="/WEB-INF/views/jsp/templates/products.jsp" />
    <put-attribute name="footer" type="template" value="/WEB-INF/views/jsp/templates/footer.jsp" />
You can also create a base template and extend from it in a similar way, look at Apache Tiles 3 documentation for more information.

Creating JSP Pages to Display required Views

Now create 4 JSP files:-
  1. header.jsp
  2. footer.jso
  3. welcome.jsp
  4. products.jsp
Header and Footer jsp's will be used on both the pages. Welcome file will be used for homepage and Products will be used for Products page.
This will include our main menu. don't worry about code here it's just bootstrap html, for showing a navigation menu, copy and paste it directly.
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      <a class="navbar-brand" href="#">Apache Tiles+Spring MVC</a>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="/SpringMVCApacheTiles">Home <span class="sr-only">(current)</span></a></li>
        <li><a href="products">Products</a></li>

      <form class="navbar-form navbar-right" role="search">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        <button type="submit" class="btn btn-default">Submit</button>

    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
We will create a simple footer with copyright info.
<div id="footer">
        <p style="text-align:center">&copy; 2015 <a href=""></a></p>
Now create the JSP for our homepage
<div id="content" style="text-align:center">
        <h2 class="tagline">This is our main content area</h2>
        <a href="products" class="bg-primary">Show All Products</a>
The last jsp file will display products from our application database. It uses JSTL to display each product from an ArrayList list of product. We will create those file as next step.
<%@ taglib uri="" prefix="c"%>
<div class="products">
     <c:forEach items="${products}" var="product">
         <div class="col-md-4" style="text-align:center">
             <img src="..." alt="..." class="img-thumbnail">
             <p>$ ${product.price}</p>

Registering Tiles Definations and Configuring Spring MVC to Use Apache Tiles 3 as View

Now create a class called MyAppConfig inside in.techyari.smat.config folder, this class will integrate SpringMVC and Tiles 3 along with other required annotations like configuring our base class to look for controllers to resolve URI mappings, refer below code..
package in.techyari.smat.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

public class MyAppConfig extends WebMvcConfigurerAdapter{
    TilesViewResolver viewResolver(){
        TilesViewResolver viewResolver = new TilesViewResolver();
        return viewResolver;

    TilesConfigurer tilesConfigurer(){
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        return tilesConfigurer;    


Creating Product domain Class for displaying Product info

Now create a new class called Product inside in.techyari.smat.model folder, this will be used later to create an arraylist of products.
package in.techyari.smat.model;

public class Product {

    private int id;
    private String name;
    private String type;
    private String imageUrl;
    private float price;

    public Product(){


    public Product(String name, String type, String imageUrl, float price) {
        super(); = name;
        this.type = type;
        this.imageUrl = imageUrl;
        this.price = price;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getType() {
        return type;

    public void setType(String type) {
        this.type = type;

    public String getImageUrl() {
        return imageUrl;

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;

    public float getPrice() {
        return price;

    public void setPrice(float price) {
        this.price = price;


Creating Controller to Resolve URL's for Home Page and Products Page

Now we need to create a controller which will resolve two url's for our site pages
  1. http://localhost:8080/SpringMVCApacheTiles/ (Base URL "/")
  2. http://localhost:8080/SpringMVCApacheTiles/products (Products page "/products")
We will also create few dummy products here to display as part of our view. create this class insidein.techyari.smat.controller package Refer below code
package in.techyari.smat.controller;

import in.techyari.smat.model.Product;

import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class AppController {
    // Map requests to Home Page
    public String welcome(Model model){
        String message = "Welcome to Spring MVC";
        model.addAttribute("welcomeMessage", message);
        return "myapp.homepage";

    // Map requests to product Page
    public String products(Model model){
        ArrayList<Product> products = getAllProducts();
        return "myapp.products";

   /* Convenience method to get a list of In Memory products, 
     In actual scenario this should come from a Repository via a Service */

    private ArrayList<Product> getAllProducts() {

        ArrayList<Product> productList = new ArrayList<Product>();

        Product p1 = new Product("Apple iPhone 5s","Smart Phone","iphone.jpg",250);
        Product p2 = new Product("Samsung Galaxy S6","Smart Phone","s6.jpg",300);
        Product p3 = new Product("LG Nexus 5","Smart Phone","nexus.jpg",100);
        Product p4 = new Product("HTC One M9","Smart Phone","htc.jpg",300);


        return productList;
That's all, we have successfully created a web app with Spring MVC and Apache Tiles 3. Run the app and see the result. Share your thoughts and comments below.

About TechYari

A web developer, blogger, amateur designer and an open source enthusiast.

No comments:

Post a comment

Contact form


Email *

Message *


Follow TechYari on


About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.