Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...
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.

Requirement

  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 (http://www.techyari.in/2015/06/getting-started-with-spring-mvc-tutorial-using-annotation-based-configuration.html ) 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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>in.techyari</groupId>
    <artifactId>SpringMVCApacheTiles</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>3.0.5</version>
        </dependency>


    </dependencies>
</project>

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;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {

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

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

    @Override
    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="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE html>
<html lang="en">
  <head>
    <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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <style type="text/css">
        a.bg-primary{padding:15px 10px;}
        a.bg-primary:hover,a.bg-primary:focus{color:white;}
        .tagline{margin-bottom:100px;}
    </style>    
  </head>
  <body>
    <div class="container">
        <div class="row">
            <div class="col-md-12" id="header">
                <tiles:insertAttribute name="header" />
            </div>
        </div>
        <div class="row">
            <div id="body">
                <tiles:insertAttribute name="body" />
            </div>
        </div>
            <div class="row">
            <div class="col-md-12" id="footer" style="margin-top:200px;border-top:1px solid gray">
                <tiles:insertAttribute name="footer" />
            </div>
        </div>

    </div>
  </body>
</html>

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"
       "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
  <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" />
  </definition>
</tiles-definitions>

products.xml

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"
       "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
  <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" />
  </definition>
</tiles-definitions>
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.
header.jsp
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>
      </button>
      <a class="navbar-brand" href="#">Apache Tiles+Spring MVC</a>
    </div>

    <!-- 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>

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

    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
We will create a simple footer with copyright info.
<div id="footer">
        <p style="text-align:center">&copy; 2015 <a href="http://www.techyari.in">Techyari.in</a></p>
    </div>
</body>
</html>
welcome.jsp
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>
</div>
products.jsp
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="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div class="products">
     <c:forEach items="${products}" var="product">
         <div class="col-md-4" style="text-align:center">
             <p>${product.name}</p>
             <img src="..." alt="..." class="img-thumbnail">
             <p>${product.type}</p>
             <p>$ ${product.price}</p>
         </div>
     </c:forEach>
</div>

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;

@Configuration
@ComponentScan(basePackages="in.techyari.smat.controller")
@EnableWebMvc
public class MyAppConfig extends WebMvcConfigurerAdapter{
    @Bean
    TilesViewResolver viewResolver(){
        TilesViewResolver viewResolver = new TilesViewResolver();
        return viewResolver;
    }

    @Bean
    TilesConfigurer tilesConfigurer(){
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions("WEB-INF/views/jsp/tiles/tiles.xml","WEB-INF/views/jsp/tiles/products.xml");
        tilesConfigurer.setPreparerFactoryClass(org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactory.class);
        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();
        this.name = name;
        this.type = type;
        this.imageUrl = imageUrl;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.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;

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

    // Map requests to product Page
    @RequestMapping("/products")
    public String products(Model model){
        ArrayList<Product> products = getAllProducts();
        model.addAttribute("products",products);
        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);

        productList.add(p1);
        productList.add(p2);
        productList.add(p3);
        productList.add(p4);

        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.


Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

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