Apache Tiles Integration with Spring MVC

1. Overview

Apache Tiles is a free, open source templating framework purely built on the Composite design pattern.

A Composite design pattern is a type of structural pattern which composes objects into tree structures to represent whole-part hierarchies and this pattern treats individual objects and composition of objects uniformly. In other words, in Tiles, a page is built by assembling a composition of sub views called Tiles.

The advantages of this framework over other frameworks include:

  • re-usability
  • ease in configuration
  • low performance overhead

In this article, we’ll focus on integrating Apache Tiles with Spring MVC.

2. Dependency Configuration

The first step here is to add the necessary dependency in the pom.xml:

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

3. Tiles Layout Files

Now we need to define the template definitions and specifically as per each page we will overwrite the template definitions for that specific page:

<tiles-definitions>
    <definition name="template-def" 
           template="/WEB-INF/views/tiles/layouts/defaultLayout.jsp">  
        <put-attribute name="title" value="" />  
        <put-attribute name="header" 
           value="/WEB-INF/views/tiles/templates/defaultHeader.jsp" />  
        <put-attribute name="menu" 
           value="/WEB-INF/views/tiles/templates/defaultMenu.jsp" />  
        <put-attribute name="body" value="" />  
        <put-attribute name="footer" 
           value="/WEB-INF/views/tiles/templates/defaultFooter.jsp" />  
    </definition>  
    <definition name="home" extends="template-def">  
        <put-attribute name="title" value="Welcome" />  
        <put-attribute name="body" 
           value="/WEB-INF/views/pages/home.jsp" />  
    </definition>  
</tiles-definitions>

4. ApplicationConfiguration and Other Classes

As part of configuration we will create three specific java classes called ApplicationInitializerApplicationController and ApplicationConfiguration:

  • ApplicationInitializer initializes and checks the necessary configuration specified in the ApplicationConfiguration classes
  • ApplicationConfiguration class contains the configuration for integrating Spring MVC with Apache Tiles framework
  • ApplicationController class works in sync with tiles.xml file and redirects to the necessary pages basing on the incoming requests

Let us see each of the classes in action:

@Controller
@RequestMapping("/")
public class TilesController {
    @RequestMapping(
      value = { "/"}, 
      method = RequestMethod.GET)
    public String homePage(ModelMap model) {
        return "home";
    }
    @RequestMapping(
      value = { "/apachetiles"}, 
      method = RequestMethod.GET)
    public String productsPage(ModelMap model) {
        return "apachetiles";
    }
 
    @RequestMapping(
      value = { "/springmvc"},
      method = RequestMethod.GET)
    public String contactUsPage(ModelMap model) {
        return "springmvc";
    }
}
public class WebInitializer implements WebApplicationInitializer {
 public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        
        ctx.register(TilesApplicationConfiguration.class);

        container.addListener(new ContextLoaderListener(ctx));

        ServletRegistration.Dynamic servlet = container.addServlet(
          "dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

There are two important classes which play a key role in configuring tiles in a Spring MVC application. They are TilesConfigurer and TilesViewResolver:

  • TilesConfigurer helps in linking the Tiles framework with the Spring framework by providing the path to the tiles-configuration file
  • TilesViewResolver is one of the adapter class provided by Spring API to resolve the tiles view

Finally, in the ApplicationConfiguration class, we used TilesConfigurer and TilesViewResolver classes to achieve the integration:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.maixuanviet.spring.controller.tiles")
public class TilesApplicationConfiguration implements WebMvcConfigurer {
    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions(
          new String[] { "/WEB-INF/views/**/tiles.xml" });
        tilesConfigurer.setCheckRefresh(true);
        
        return tilesConfigurer;
    }
    
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        TilesViewResolver viewResolver = new TilesViewResolver();
        registry.viewResolver(viewResolver);
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
          .addResourceLocations("/static/");
    }
}

5. Tiles Template Files

Till now we had finished the configuration of Apache Tiles framework and the definition of the template and specific tiles used in the whole application.

In this step, we need to create the specific template files which have been defined in the tiles.xml.

Please find the snippet of the layouts which can be used as a base to build specific pages:

<html>
    <head>
        <meta 
          http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title><tiles:getAsString name="title" /></title>
        <link href="<c:url value='/static/css/app.css' />" 
            rel="stylesheet">
        </link>
    </head>
    <body>
        <div class="flex-container">
            <tiles:insertAttribute name="header" />
            <tiles:insertAttribute name="menu" />
        <article class="article">
            <tiles:insertAttribute name="body" />
        </article>
        <tiles:insertAttribute name="footer" />
        </div>
    </body>
</html>

6. Conclusion

This concludes the integration of Spring MVC with Apache Tiles.

You can find the full implementation in the following github project.

Related posts:

Java Byte Array to InputStream
Java Program to Implement Miller Rabin Primality Test Algorithm
Spring MVC Custom Validation
Refactoring Design Pattern với tính năng mới trong Java 8
Hướng dẫn Java Design Pattern – Object Pool
Command-Line Arguments in Java
Java Program to Perform Left Rotation on a Binary Search Tree
Converting between an Array and a List in Java
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to Show the Duality Transformation of Line and Point
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement Bellman-Ford Algorithm
Spring Boot - Flyway Database
Java program to Implement Tree Set
Java Program to Perform Deletion in a BST
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Thực thi nhiều tác vụ cùng lúc như thế nào trong Java?
Ignore Null Fields with Jackson
Java Program to Create the Prufer Code for a Tree
Introduction to Java 8 Streams
Java Program to Implement Iterative Deepening
Java 8 StringJoiner
Java Program to Implement the RSA Algorithm
@Lookup Annotation in Spring
Java Program to Implement Strassen Algorithm
Getting Started with GraphQL and Spring Boot
Create a Custom Exception in Java
Java Program to Implement Interpolation Search Algorithm
Java Program to Implement Caesar Cypher
Mockito and JUnit 5 – Using ExtendWith
Java Program to Check if a Directed Graph is a Tree or Not Using DFS