• Get In Touch
May 21, 2017

An Introduction to the Apache Tiles Framework

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Tiles framework provides a templating mechanism that allows you to separate the layout from content of pages. Tiles could be used with or without Struts (Not common), and it comes with the struts release.

Tiles enable the developers to define templates for the web application, and then use the layouts to populate the web pages. A layout represents the structure of a page. It is simply a JSP page. You may think of the layout as a template with placeholders. You can place other JSPs in these placeholders declaratively.

The layout of the web pages could be easily changed according to the business requirement and it makes it easier to change the look and feel of the whole web site . Also the whole web site could have the consistent look and feel by using the same layout.

Create a simple tiles application

This section guides us to create our first simple tiles application. The essential steps to create a Tiles application are as follows;
1. Create a new Struts web application or add Tiles to an existing Struts application.
2. Edit the struts-config file and uncomment or add the section that refers to the “Tiles PlugIn”.

        <plug-in className="org.apache.struts.tiles.TilesPlugin" >
              <set-property property="definitions-config"
                                     value="/WEB-INF/tiles-defs.xml" />
          <set-property property="moduleAware" value="true" />
            </plug-in>
  1. Create the Tiles definitions file (The file name should match the one defined in the struts-config file as above, ‘tiles-defs.xml in this case) in the /WEB-INF directory of the application.
  2. Copy the file struts-tiles.jar from the Struts release to WEB-INF/lib directory of the web application, if the file is not there already.
  3. Add the init-parm section to the Action Servlet definition in the web.xml file.
           <init-param>
    <param-name>chainConfig</param-name>
            <param-value>
                org/apache/struts/tiles/chain-config.xml
            </param-value>
    </init-param>
  1. Make sure at the top of each JSP page that will use the Tiles, there is a line that declares the Tiles custom tag library.
    <%@ taglib url="http://struts.apache.org/tags-tiles" 
        prefix="tiles" %>

Example

We will go through creating a Struts Tiles application named ‘HelloWorldTile’ application. It has one page which shows a string ‘Hello World!’ on the screen.
The page has a common layout with a header, a menu, footer and the content.
The sample application is based on the sample application that comes with the Struts release.

Configuration of struts-config XML file

Simply add the tiles plugin to the files struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
   <form-beans>
   </form-beans>
   <global-exceptions>
    </global-exceptions>
    <global-forwards>
        <!-- Default forward to "Welcome" action -->
        <forward   name="welcome"     path="/welcome.do"/>
    </global-forwards>    <action-mappings>
            <!-- Default "Welcome" action -->
            <!-- Forwards to Welcome.jsp -->
       <action           path="/welcome"
          forward=".helloWorld"/>
   </action-mappings>
    <message-resources parameter="MessageResources" />
Tiles plugin -->
   <plug-in className="org.apache.struts.tiles.TilesPlugin" >
     <set-property property="definitions-config"
                      value="/WEB-INF/tiles-defs.xml" />
      <set-property property="moduleAware" value="true" />
    </plug-in>
  <!-- =================================================== 
Validator plugin -->
 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
   <set-property
       property="pathnames"
        value="/org/apache/struts/validator/validator-rules.xml,
               /WEB-INF/validation.xml"/>
 </plug-in>
</struts-config>

Configuration of tiles config file

Create an XML file with the following content.

<!DOCTYPE tiles-definitions PUBLIC
  "-//Apache Software Foundation//DTD Tiles Configuration//EN"
  "http://jakarta.apache.org/struts/dtds/tiles-config.dtd">
<tiles-definitions>
  <definition name=".baseLayout" path="/WEB-INF/jsp/layouts/baselayout.jsp">
      <put name="title" value="Base Layout"/>
       <put name="header" value="/WEB-INF/jsp/common/header.jsp"/>
       <put name="menu" value="/WEB-INF/jsp/common/menu.jsp"/>
       <put name="content" value="/WEB-INF/jsp/common/blank.jsp"/>
       <put name="footer" value="/WEB-INF/jsp/common/footer.jsp"/>
   </definition>
    <definition name=".helloWorld" extends=".baseLayout">
       <put name="title" value="Hello World"/>
        <put name="content" value="/WEB-INF/jsp/pages/helloworld.jsp"/>
    </definition >
</tiles-definitions>

The file has two Tiles definitions, that is the ‘.baseLayout’ and the ‘.helloWorld’ which extends the first definition.
The ‘.baseLayout’ is associated with a layout file named baselayout.jsp. And in each Tiles definition, it defines the placeholder names of different part of the page, e.g. header and footer, and it defines the associated JSP files for each placeholders.

Note:

The Tiles definition supports the inheritance that is the child definition could extend the base definition and inherit all the attributes of the base one. And the child definition can override the attributes defined in the base definition, e.g. the ‘.helloWorld’ defines the ‘title’ as “Hello World”, which overrides the default “Base Layout” in the base definition.
Tiles definitions could not be used as the URL on the browser, e.g. you cannot use the URL “http://localhost:8080/HelloWorldTile/.helloWorld”.
The definitions are commonly used as the forwarding path of the action mappings.

Configuration of tiles in web.xml file

Create an XML file with the following content.

<?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
 <display-name>Struts Blank Application</display-name>
  <!-- Standard Action Servlet Configuration -->
 <servlet>
    <servlet-name>action</servlet-name>
   <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   <init-param>
     <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
   <init-param>
       <param-name>chainConfig</param-name>
        <param-value>org/apache/struts/tiles/chain-config.xml</param-value>
   </init-param>
    <load-on-startup>2</load-on-startup>
 </servlet>
  <!-- Standard Action Servlet Mapping -->
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Defining layout

Create a jsp file with the following content.

<%-- Include common set of tag library declarations for each layout --%>
<%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%>
<html>
   <head>
        <title>
            <tiles:getAsString name="title" ignore="true"/>
        </title>
    </head>
    <body>
       <table border="1">
            <tr>
                <td><tiles:insert attribute="header"/></td>
            </tr>
        </table>
        <table border="1">
            <tr>
              <td>
                    <tiles:insert attribute='menu' ignore="true"/>
                </td>
                <td>
                   <table border="1">
                        <tr>
                            <td>
                                <tiles:insert attribute='content'/>
                            </td>
                     </tr>
                    </table>
                    <table border="1">
                        <tr>
                           <td>
                              <tiles:insert attribute="footer"/>
                            </td>
                        </tr>
                   </table>
                </td>
            </tr>
        </table>
   </body>
</html>

In the layout file, we use ‘tiles:getAsString’ tag to display the title of the page.
To insert the JSPs into the placeholders in the layout, we use ‘tiles:insert’ custom tag which inserts any page or web resources that framework refers to. The attribute names must match the names defined in the ‘tiles-defs.xml’ file.
For example,

‘<tiles:insert attribute='menu' ignore="true"/>’ 

inserts a menu into the page. The JSP file associated with the ‘menu’ attribute is defined in the ‘tiles-defs.xml’ file, which is ‘/WEB-INF/jsp/common/menu.jsp’.
Note: The attribute ‘ignore=”true”’ in the Tiles custom tag defines whether the Tiles ignore the missing parameter. If the attribute is set to ‘false’, then the Tiles framework will throw an exception in case the parameter is missing (e.g. ‘content’ attribute is not defined in the ‘tiles-defs.xml’ file)

Tiles in web pages

The JSP files that will be inserted into different parts of the layout are as follows.

taglibs.jsp
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
header.jsp
<%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%>
<div>Header Item</div>footer.jsp
    <%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%>
    <div>Footer Item</div>
menu.jsp
    <%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%>
    <div>Menu Items</div>
helloworld.jsp
    <%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%>
    <div>Hello World!</div>

Packaging and deploying

We use ant build tool to deploy the web application. The build-web.xml file is as follows.

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Hello World - Sub build" basedir=".">
    <property   name="web.src.webroot.dir" value="${root.dir}/SVN_LOCAL/web/WebRoot"/>
   <property name="web.build.dir" value="${root.dir}/BUILD_LOCAL/web/build
/classes"/>
    <property name="web.dist.dir" value="${root.dir}/BUILD_LOCAL/web/dist"/>
    <property name="web.war.file" value="${web.dist.dir}/${web.war.filename}"/>
    <property name="web.deployment.descriptor.dir" value="${root.dir}/SVN_LOCAL
    /web/descriptor"/>
    <property name="web.build.web.xml.name" 
value="${web.deployment.descriptor.dir}/web.xml"/>
    <property name="tomcat.home.webapps.dir" 
    value="${absolute.tomcat.home.dir}/webapps/"/>
    <path id="classpath.web">
        <pathelement location="."/>
        <fileset dir="${lib.dir}">
            <include name="**/*.jar"/>
       </fileset>
    </path>
    <target name="clean.web" description="Delete web build directory">
        <delete dir="${web.build.dir}"/>
        <delete dir="${web.dist.dir}"/>
   </target>
    <target name="make.web.dir" depends="clean.web" description="Create web build directory"><mkdir dir="${web.build.dir}"/><mkdir dir="${web.dist.dir}"/>
    </target><target name="create.web.war" depends="make.web.dir"   description="Create web war">
<war destfile="${web.war.file}" webxml="${web.build.web.xml.name}">
        <lib dir="${lib.dir}">       <include name="*.jar"/></lib>
                <fileset dir="${web.src.webroot.dir}">
            <include name="index.jsp"/>
            </fileset>
            <webinf dir="${web.src.webroot.dir}">
                <include name="**/*.jsp"/>
                <exclude name="index.jsp"/>
            </webinf>
            <webinf dir="${web.deployment.descriptor.dir}">
                <include name="**/*.xml"/>
            </webinf>
        </war>
    </target>
    <target name="deploy.web.war" depends="create.web.war" 
    description="Deploy web war">
        <copy file="${web.war.file}" todir="${tomcat.home.webapps.dir}"/>
   </target>
</project>

The ‘deploy.web.war’ target is used to deploy the web application into the ‘webapps’ folder of Tomcat.
Note: The absolute locations of the folders, e.g. tomcat_home, are configured in the build.properties file. You may need to modify this file a bit to suit the configurations in your box.

Testing

To test the ‘HelloWorldTile’ web application, you need to start Tomcat and open a browser to the URL ‘http://localhost:8080/HelloWorldTile’ and you should be able to see a page with some HTML elements bearing the content (“Header Item”,”Menu Items”,”Hello world” and “Footer item”) we set in the web pages. (the jsp files).

Conclusion

This tutorial has taken has through the basic steps that makes us familiar with the Tiles Framework. Having gone through it, you are expected to have understood the basics of how the Tiles Framework operates.

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]