Struts 2

Struts JSP Example

Apache Struts2 is an elegant, extensible framework for creating the enterprise-ready Java web applications. The framework is designed to streamline the development cycle i.e. from building to deploying and to maintaining the applications over time. In this example, we will show developers how to create a simple Hello World example in Struts2.

1. Introduction

1.1 Struts Framework

  • Struts framework is based on a set of Java technologies like Servlet, JSP, JSTL, XML, Velocity etc which provides the MVC (i.e. Model View Controller) implementation and a ready to use Validation framework
  • The power of Struts lies in its model layer by which it can be integrated with other Java technologies, for e.g.: JDBC, EJB, Spring, Hibernate etc
  • Struts framework is a complete web framework as it provides the Web Form Components, Validators, Error Handling, Internationalization, Tiles and its own Controller component
  • Struts2 framework also supports the annotation based configurations which are easy to use and are more intuitive
  • Struts2 also comes with powerful APIs to configure the Interceptors that greatly reduce the coupling in an application

1.1.1 How Struts Work?

When developers use Struts, the framework provides them with a Controller Servlet i.e. ActionServlet which is defined in the Struts libraries that are included in an application. This controller servlet is automatically registered in the deployment descriptor file (web.xml) as shown in the below figure.

Fig. 1: Struts2 Request Response Overview
Fig. 1: Struts2 Request Response Overview

The controller servlet uses a struts-config.xml file to map the incoming requests to the Struts Action objects and instantiate any ActionForm object associated with the action to temporarily store the form data. The Action Object processes requests by using it’s execute() method, while making the use of any stored data. Once the Action Object processes a request, it stores any new data in the same or in a different result bean and forwards the response to an appropriate view.

1.1.2 Struts2 Advantages

  • The Action classes code is not tightly coupled to the Struts framework or the Servlet API
  • ActionForm is a simple POJO class which do not need to implement any interface or extend from any class
  • Unit testing of the Struts2 Action Class is easy because it doesn’t need the complex HttpServletRequest and HttpServletResponse objects
  • The use of annotations results in the reduction of code complexity
  • Struts2 tags provide the style sheet driven form tags which reduce the coding efforts and coding of the form validation

Now, open up the Eclipse IDE and let’s see how to implement a simple hello world application in the struts2 framework!

2. Struts JSP 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. 2: Struts2 Application Structure
Fig. 2: Struts2 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. 3: Create Maven Project
Fig. 3: 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. 4: Project Details
Fig. 4: Project Details

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

Fig. 5: Archetype Selection
Fig. 5: 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. 6: Archetype Parameters
Fig. 6: 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>Struts2Jsp</groupId>
	<artifactId>Struts2Jsp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Struts2 Core 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, OGNL etc. The updated file 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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2Jsp</groupId>
	<artifactId>Struts2Jsp</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>
	</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. 7: Java Package Creation
Fig. 7: Java Package Creation

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

Fig. 8: Java Package Name (com.jcg.struts2.jsp)
Fig. 8: Java Package Name (com.jcg.struts2.jsp)

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. 9: Java Class Creation
Fig. 9: 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.jsp.

Fig. 10: Java Class (LinkAction.java)
Fig. 10: 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. But the action servers in two important capacities i.e.

  • First, the action class is not required to implement any interface or extend any class
  • Second, the action class is required to create an execute() method to put all the business logic inside and return a string value to tell the application where to redirect

Add the following code to it:

LinkAction.java

package com.jcg.struts2.jsp;

public class LinkAction {

	private String user_name;

	public String getUser_name() {
		return user_name;
	}

	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}

	// All Struts Logic Goes In This Method
	public String execute() {
		return "success";
	}
}

3.3 Configuration Files

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

3.3.1 Struts Configuration File

To configure the struts2 framework, developers need to implement a configuration file i.e. struts.xml. In this file, we 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. 11: XML File Creation
Fig. 11: XML File Creation

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

Fig. 12: Wizard Selection
Fig. 12: Wizard Selection

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

Fig. 13: struts.xml
Fig. 13: 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">
		<action name="Login">
			<result>views/login.jsp</result>
		</action>
		<action name="Welcome" class="com.jcg.struts2.jsp.LinkAction">
			<result name="success">views/welcomeUser.jsp</result>
		</action>
	</package>
</struts>

3.3.2 Web Deployment Descriptor

The web.xml file declares a filter (i.e. StrutsPrepareAndExecuteFilter) to configure the struts2 framework in the application. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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 2 Web Application</display-name>
   <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>
</web-app>

3.4 Creating JSP View

Let us write a simple JSP to illustrate this tutorial. Right-click on Struts2Jsp/src/main/webapp/views folder, New -> JSP File.

Fig. 14: JSP Creation
Fig. 14: JSP Creation

Verify the parent folder location as: Struts2Jsp/src/main/webapp/views and enter the filename as: login.jsp. Click Finish.

Fig. 15: login.jsp
Fig. 15: login.jsp

Repeat the step (i.e. Fig. 14) and enter the filename as: welcomeUser.jsp. Click Finish.

Fig. 16: welcomeUser.jsp
Fig. 16: welcomeUser.jsp

3.4.1 Application’s Login Page

A login page uses the struts2 tags for displaying the username and password input fields along with a submit button. Add the following code to it:

login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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 JSP Example</title>
   </head>
   <body>
      <h1>Struts2 Hello World Example</h1>
      <s:form action="Welcome">
         <s:textfield name="user_name" label="Username" />
         <s:password name="password" label="Password" />
         <s:submit />
      </s:form>
   </body>
</html>

3.4.2 Application’s Welcome Page

A view page to display the welcome message to the user. Add the following code to it:

welcomeUser.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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 JSP Example</title>
   </head>
   <body>
      <h1>Struts2 Hello World Example</h1>
      <h4>
         Hello <s:property value="user_name"/>
      </h4>
   </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:8085/Struts2Jsp/Login.action

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

Fig. 18: Login Page
Fig. 18: Login Page

Now, enter any random username/password and click on Submit button. Developers should see the following result if everything is fine with the application.

Fig. 19: Welcome User Page
Fig. 19: Welcome User Page

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, developers learned how to download, create a new project in Eclipse IDE, and add Struts2 libraries to write a simple struts2 example. 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 the struts2 framework for the beginners.

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

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.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
MAS
MAS
2 years ago

Thanks!

syedraja
syedraja
1 year ago

super! helpful for every student..

Back to top button