Struts 2

Struts Tiles Plugin in Eclipse Example

Struts Tiles framework is a layout framework, which allows users to maintain a standard look of the header, footer, and menu across all of the web pages efficiently. It is used for both page decorating and componentization. In this part, we will discuss the Tiles Framework and its integration with Struts2.

1. Introduction

1.1 Struts Tiles Framework

Tiles are used to create the reusable presentation components. Consider an example of a web application whose web-page layout has a header, body and footer part as shown below.

Fig. 1: Web Application Layout
Fig. 1: Web Application Layout

Generally, we have two ways to create the base layout of an application. Developers can add a header and a footer section on all pages of the website or they can create the header and the footer in a separate file and then they can include the header and footer into each page by using the jsp:include tag.

In a first way, all pages contain the header and footer source code. Thus by using the first way, when the header or footer will change, the corresponding changes need to be made in all the pages. The second way looks excellent because if developers are changing the header or the footer there is no need to change all the pages.

Suppose in future developers need to add a menu section to each page, as shown in the picture below. In this case, developers have to change all pages because they have to include the command of the menu on each page.

Fig. 2: Struts Tiles Layout
Fig. 2: Struts Tiles Layout

In this situation, the tiles framework is the best way to develop the application’s page layout. Tiles use a separate layout file, which contains the container of the layout. When the layout will be changed only the layout file and the tiles configuration files have to change by the developer, thus saving time and increasing applications efficiency.

1.1.1 Steps to integrate the Tiles framework

Developers can enable the tiles in the Struts framework by writing the struts-configuration file. Here is an example of the sample configuration file:

<plug-in className="org.apache.struts.tiles.TilesPlugin">
    <set-property property="definitions-config"
        value="/WEB-INF/tiles-definitions.xml" />
    <set-property property="moduleAware" value="true" />
</plug-in>

Let’s look at some basic details:

  • Developers can see the definitions-config parameter which is set to the value: /WEB-INF/tiles-definitions.xml. So developers will have to create a file called tiles-definitions.xml in the WEB-INF directory
  • There are two ways in which developers can specify the tiles definition and their attributes. One is using the JSP Tile Definition and the other way is using the XML Tile Definition

1.1.2 Tiles Framework Advantage

    • Centralized Page Customization: Developers can customize the layout of all the pages on a single page (i.e. centralized page) only
    • Code Reusability: A single part e.g. header or footer can be used in many pages
    • Easy to Modify: If any part (i.e. tile) is modified, developers don’t need to change the same in many pages, thereby saving coding and time efforts
    • Easy to Remove: If any part (i.e. tile) of the page is removed, developers don’t need to remove the code from all the pages i.e. they can simply remove the tile from the layout manager page (i.e. base layout page)

Now, open up the Eclipse IDE and let’s see how to implement the tiles layout in the struts2 framework!

2. Struts Tiles Plugin Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Struts Tiles Plugin Application Structure
Fig. 3: Struts Tiles Plugin Application Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project
Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 5: Project Details
Fig. 5: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 6: Archetype Selection
Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters
Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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>Struts2Tiles</groupId>
	<artifactId>Struts2Tiles</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Struts2 Core, Struts2 Tiles etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependency for the Struts2 framework. The rest dependencies will be automatically resolved by Maven, such as Struts2 Core, Struts2 Tiles, and Struts2 Taglib etc. The updated file will have the following code:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>Struts2Tiles</groupId>
   <artifactId>Struts2Tiles</artifactId>
   <packaging>war</packaging>
   <version>0.0.1-SNAPSHOT</version>
   <dependencies>
      <!-- Servlet API Dependency -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.1.0</version>
      </dependency>
      <!-- Struts2 Core Framework Dependency -->
      <dependency>
         <groupId>org.apache.struts</groupId>
         <artifactId>struts2-core</artifactId>
         <version>2.3.24.1</version>
      </dependency>
      <!-- Struts2 Tiles Framework Dependency -->
      <dependency>
         <groupId>org.apache.struts</groupId>
         <artifactId>struts2-tiles-plugin</artifactId>
         <version>2.3.24.1</version>
      </dependency>
   </dependencies>
   <build>
      <finalName>${project.artifactId}</finalName>
   </build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.struts2.tiles.

Fig. 9: Java Package Name (com.jcg.struts2.tiles)
Fig. 9: Java Package Name (com.jcg.struts2.tiles)

Once the package is created in the application, we will need to create the Struts2 action class. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation

A new pop window will open and enter the file name as: LinkAction. The action class will be created inside the package: com.jcg.struts2.tiles.

Fig. 11: Java Class (LinkAction.java)
Fig. 11: Java Class (LinkAction.java)

3.2.1 Implementation of Action Class

Actions are the core of the Struts2 framework, as they are for any Model View Controller framework. Each URL is mapped to a specific action, which provides the processing logic necessary to serve the request coming from the user. But the action also serves in two other important capacities i.e.

  • First, the action plays an important role in the transfer of data from the request through to the view, whether it’s a JSP or the other type of result
  • Second, the action must assist the framework in determining which result should render the view that will be returned in response to the request

Add the following code to it:

LinkAction.java

package com.jcg.struts2.tiles;

import com.opensymphony.xwork2.ActionSupport;

public class LinkAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	public String welcome() {
		return "welcome";		
	}

	public String friends() {
		return "friends";		
	}

	public String office() {
		return "office";		
	}
}

3.3 Configuration Files

Let’s write all the configuration files involved in this application.

3.3.1 Struts Configuration File

To configure the struts framework, developers need to implement a configuration file i.e. struts.xml. In this file, they will define the result tag which maps a particular action with a JSP page. Right-click on the src/main/resources folder, New -> Other.

Fig. 12: XML File Creation
Fig. 12: XML File Creation

A new pop window will open and select the wizard as a XML file.

Fig. 13: Wizard Selection
Fig. 13: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as: Struts2Tiles/src/main/resources and enter the file name as: struts.xml. Click Finish.

Fig. 14: struts.xml
Fig. 14: struts.xml

Once the XML file is created, we will add the following code to it:

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <package name="default" extends="struts-default">
      <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
      </result-types>
      <action name="*Link" method="{1}" class="com.jcg.struts2.tiles.LinkAction">
         <result name="welcome" type="tiles">welcome</result>
         <result name="friends" type="tiles">friends</result>
         <result name="office" type="tiles">office</result>
      </action>
   </package>
</struts>

3.3.2 Struts Tile Configuration File

In tiles.xml we have defined a template i.e. the base layout. This layout contains attributes such as Header, Title, Body, Menu, and Footer. This base layout is then extended and the new definitions for the welcome and customer pages are defined. Add the following code to it:

tiles.xml

<?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="baseLayout" template="/baseLayout.jsp">
		<put-attribute name="title" value="Template" />
		<put-attribute name="header" value="/header.jsp" />
		<put-attribute name="menu" value="/menu.jsp" />
		<put-attribute name="body" value="/body.jsp" />
		<put-attribute name="footer" value="/footer.jsp" />
	</definition>
	<definition name="welcome" extends="baseLayout">
		<put-attribute name="title" value="Welcome" />
		<put-attribute name="body" value="/welcome.jsp" />
	</definition>
	<definition name="friends" extends="baseLayout">
		<put-attribute name="title" value="Friends" />
		<put-attribute name="body" value="/friends.jsp" />
	</definition>
	<definition name="office" extends="baseLayout">
		<put-attribute name="title" value="Office" />
		<put-attribute name="body" value="/office.jsp" />
	</definition>
</tiles-definitions>

Do note, we have to override the default layout and change the content of the body and the title.

3.3.3 Web Deployment Descriptor

The web.xml file declares a Tile Listener (i.e. StrutsTilesListener) to configure the Tiles framework in the application. Also, an input configuration file i.e. /WEB-INF/tiles.xml is passed as an argument which contains the Tiles definition for the web application. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="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" id="WebApp_ID" version="2.5">
   <display-name>StrutsTiles</display-name>
   <context-param>
      <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
      <param-value>/WEB-INF/tiles.xml</param-value>
   </context-param>
   <listener>
      <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
   </listener>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

3.4 Creating JSP View

We will define the template for our web application in a JSP file called baseLayout.jsp. This template will contain the different segments of the web page (i.e. Header, Footer, Menu etc). Let us write a simple base layout in Struts2Tiles/src/main/webapp. Right-click on Struts2Tiles/src/main/webapp folder, New -> JSP File.

Fig. 15: JSP Creation
Fig. 15: JSP Creation

Verify the parent folder location as: Struts2Tiles/src/main/webapp and enter the filename as: baseLayout.jsp. Click Finish.

Fig. 16: baseLayout.jsp
Fig. 16: baseLayout.jsp

Repeat the step (i.e. Fig. 15). Verify the parent folder location as: Struts2Tiles/src/main/webapp and create the following new JSP files i.e.

  • header.jsp
  • footer.jsp
  • body.jsp
  • menu.jsp
  • welcome.jsp
  • office.jsp
  • friends.jsp

3.4.1 Application’s Base Layout

Add the following code to it:

baseLayout.jsp

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title><tiles:insertAttribute name="title" ignore="true" /></title>
   </head>
   <body>
      <table border="1" cellpadding="2" cellspacing="2" align="center">
         <tr>
            <td height="30" colspan="2">
               <tiles:insertAttribute name="header" />
            </td>
         </tr>
         <tr>
            <td height="250">
               <tiles:insertAttribute name="menu" />
            </td>
            <td width="350">
               <tiles:insertAttribute name="body" />
            </td>
         </tr>
         <tr>
            <td height="30" colspan="2">
               <tiles:insertAttribute name="footer" />
            </td>
         </tr>
      </table>
   </body>
</html>

3.4.2 Application’s Header

Add the following code to it:

Header.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		 <title>Struts2 Tiles Example</title>
    </head>
   <body>
		<div align="center" style="font-weight:bold">TV Shows</div>
    </body>
</html>

3.4.3 Application’s Footer

Add the following code to it:

footer.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		 <title>Struts2 Tiles Example</title>
    </head>
   <body>
		<div align="center">© javacodegeek.com</div>
    </body>
</html>

3.4.4 Application’s Body

Add the following code to it:

body.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		 <title>Struts2 Tiles Example</title>
    </head>
   <body>
		<p>!! Sample Body Content !!</p>
    </body>
</html>

3.4.5 Application’s Menu

Add the following code to it:

menu.jsp

<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		 <title>Struts2 Tiles Example</title>
    </head>
   <body>
   		<div id="friendsLinkDiv">
   			<a id="friendsLinkId" href="<s:url action="friendsLink"/>">Friends</a>
   		</div>
		<div id="officeLinkDiv">
			<a id="officeLinkId" href="<s:url action="officeLink"/>">The Office</a>
		</div>		
    </body>
</html>

3.4.6 Application’s Welcome Page

Add the following code to it:

welcome.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
   		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		 <title>Struts2 Tiles Example</title>
    </head>
   <body>
		<div align="center">Welcome Guest</div>
    </body>
</html>

3.4.7 Application’s Friends Menu Page

Add the following code to it:

friends.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Struts2 Tiles Example</title>
    </head>
    <body>
        <p>More Details About The Friends Tv Show Goes Here !!</p>
    </body>
</html>

3.4.8 Application’s Office Menu Page

Add the following code to it:

office.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Struts2 Tiles Example</title>
    </head>
    <body>
        <p>More Details About The Office Tv Show Goes Here !!</p>
    </body>
</html>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 17: How to Deploy Application on Tomcat
Fig. 17: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8082/Struts2Tiles/welcomeLink.action

Server name (localhost) and port (8082) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 18: Welcome Page
Fig. 18: Welcome Page

Now click on Friends link to submit the action in the struts2 framework and to get the final redirected page. Developers should see the following result if everything is fine with their application.

Fig. 19: Friends Page
Fig. 19: Friends Page

That’s all for this post. Happy Learning!

6. Conclusion

In this section, developers learned how to download, create a new project in Eclipse IDE, and add Struts2 & Tiles framework library files to write a simple Struts2 Tiles layout tutorial. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Struts Tiles framework for the beginners.

Download
You can download the full source code of this example here: Struts2Tiles

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hareesh L
Hareesh L
3 years ago

hi i have tried applicaton in pivotal server
and getting the error
HTTP Status [404] – [Not Found]Type Status Report
Message /Struts2Tiles/welcomeLink.action
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Back to top button