Saturday, 1 March 2014

JSP + Apache Tiles Example

Hello all,
This sample application will show you how to use apache tiles using JSP in your maven web application project. so lets get started.
Follow these steps to make your project:

Application Type: Maven Web Application
Apache Tiles: 2.2.2 version
Web Server: Tomcat 7.0.50

Download Source Code: Click here

web.xml Configuration Code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <context-param>
<param-name>
            org.apache.tiles.definition.DefinitionsFactory.DEFINITIONS_CONFIG
        </param-name>
<param-value>
            /WEB-INF/myTilesConfigFile.xml
        </param-value>
    </context-param>
    <listener>
    <listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>jsp/home.jsp</welcome-file>
    </welcome-file-list>

</web-app>

myTilesConfigFile.xml Configuration

<?xml version="1.0" encoding="UTF-8"?>
<!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="homePage" template="/jsp/template.jsp">
        <put-attribute name="header" value="/jsp/defaultHeader.jsp" />
        <put-attribute name="menu" value="/jsp/defaultMenu.jsp" />
        <put-attribute name="body" value="/jsp/home_body.jsp" />
        <put-attribute name="footer" value="/jsp/defaultFooter.jsp" />
    </definition>

</tiles-definitions>



Template.jsp

<%-- 
    Document   : defaultFooter
    Created on : Mar 1, 2014, 1:38:55 PM
    Author     : Umair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<html>
    <body style="width:100%;height:100%">
        <table border="1" cellspacing="0" cellpadding="0" style="width:100%;height:100%">
            <tr>
                <td colspan="2">
                    <tiles:insertAttribute name="header" /></td>
            </tr>
            <tr>
                <td>
                    <tiles:insertAttribute name="menu" /></td>
                <td>
                    <tiles:insertAttribute name="body" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <tiles:insertAttribute name="footer" /></td>
            </tr>
        </table>
    </body>

</html>