Enterprise Java

Struts tutorial for beginners

Apache Struts is an open source framework for developing Java Enterprise web applications. It uses Java Servlet API to implement the web applications based on Model-View-Controller (MVC) design pattern.

As the latest version of Struts is currently Struts 2, we describe the Struts 2 framework here.

1. How Struts works

Struts 2 MVC is realised by three core framework components: actions, results, and the ServletFilter. The diagram below shows how these three components interact with each other.

Struts 2 architecture

1.1. Servlet Filter

The servlet filter acts as a controller in Struts 2. It inspects each incoming request to determine which Struts 2 action should handle the request. The framework handles all of the controller work for the application. All request URLs need to be mapped to actions with XML-based configuration files or Java annotations.

1.2. Interceptors

Interceptors execute before and after the request processing. They provide cross-cutting tasks so that they can be easily reused as well as separated from other architectural concerns. For example, validation parameters before invoking login action.

1.3. Action

Action handles the client requests in two different ways. First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request.

1.4. Result

Result is a JSP or HTML page to create a view for client response. Struts 2 provides their own tags that we can use in JSP pages to create a response. Struts tags are great example of JSP Custom Tags.

2. Struts Simple Login Example

Now lets create a simple example with Struts2. The following example is implemented in Eclipse 3.6 and run on tomcat 8.

First, create a Dynamic web project in Eclipse.

dynamic-web-application-500

Then convert the project to a maven project. The maven pom file is generated in the root directory of the project.

convert-to-maven-project-499

Now, lets have a look at the pom.xml file.

2.1. pom.xml

Open the pom.xml file and add Struts2 core dependency which is the only dependency that we need here. The final pom.xml will look like below.

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

    <dependencies>
        <dependency>
            <groupId>org.apache.Struts</groupId>
            <artifactId>Struts2-core</artifactId>
            <version>2.3.24</version>
        </dependency>
        <dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <resources>
            <resource>
                <directory>src/com/java/code/geeks/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>

I added the dependencies and override the fileName. The fileName is changed to avoid adding version number to WAR file during maven build. Also, the resource folder is configured here. Then, during maven build the resource file will be copied to /WEBINF/classes which make the resources available for the web application.

Now, if we do a maven build of the application all required jars will be added to the application lib directory and shown in Maven Dependencies section of the project.

Maven Dependency - Struts 2

2.2. web.xml

The web.xml, web application descriptor file represents the core of the Java web application, so it is appropriate that it is also part of the core of the Struts framework. In the web.xml file, Struts defines its Controller, the Servlet Filter class that initializes the Struts framework and handles all requests. This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave.

We set org.apache.Struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter as a Servlet Filter to the web application here. Then, we mapped the Struts 2 dispatcher to /*, so Struts 2 has a crack at all incoming requests.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2tutorial</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>

  <welcome-file-list>
    <welcome-file>/login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Tip

To split up the the dispatcher phases, FilterDispatcher is deprecated since Struts 2.1.3. If working with older versions, you need to use org.apache.Struts2.dispatcher.FilterDispatcher.

2.3. Action Class

We only have one action class which implements Action interface. The LoginAction needs to implement the execute method to handle client requests and return proper result.

LoginAction.java

package com.java.code.geeks.action;

import com.opensymphony.xwork2.Action;

public class LoginAction implements Action {

    @Override
    public String execute() throws Exception {
        if (validateString(getUsername()) && validateString(getPassword()))
            return "SUCCESS";
        else return "ERROR";
    }

    //Java Bean to hold the form parameters
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private boolean validateString(String str) {
        if (str != null && !str.equals(""))
            return true;
        return false;
    }
}

The LoginAction also plays as a java bean which includes getter and setter methods. Struts will handle the mapping between the request parameters to the action class variables.

2.4. Result pages

There are three Jsps in this tutorial which will be used by the web application. We are using Struts tags to create Jsp pages.

2.4.1. Login page

You can see now form fields are username and password. They are used in LoginAction class.

login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/Struts-tags" prefix="s"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
        <title>Login Page</title>
    </head>
    <body>
        <h3>Welcome to Struts 2 Login Tutorial</h3>
    <s:form action="home">
        <s:textfield name="username" label="User Name"></s:textfield>
        <s:textfield name="password" label="Password" type="password"></s:textfield>
        <s:submit value="Login"></s:submit>
    </s:form>
    </body>
</html>

2.4.2. welcome page

The Struts tag s:property is used to get request attributes which is username here.

welcome.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/Struts-tags" prefix="s"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
        <title>Welcome To Struts 2 Tutorial</title>
    </head>
    <body>
        <h3>Welcome <s:property value="username"></s:property>!</h3>
    </body>
</html>

2.4.3. Error page

This is a simple JSP page which includes error message and including login page in response.

error.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/Struts-tags" prefix="s"%>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
        <title>Error Page</title>
    </head>
    <body>
        <h4>User Name or Password is wrong</h4>
        <s:include value="login.jsp"></s:include>
    </body>
</html>

2.5. Struts.xml

The Struts.xml is created in resources folder in src. The Struts configs are responsible for mapping action and result in the web application.

Struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE Struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://Struts.apache.org/dtds/Struts-2.3.dtd">
<Struts>
    <package name="default" namespace="/" extends="Struts-default">
        <action name="login">
            <result>/login.jsp</result>
        </action>
        <action name="home" class="com.java.code.geeks.action.LoginAction">
            <result name="SUCCESS">/welcome.jsp</result>
            <result name="ERROR">/error.jsp</result>
        </action>
    </package>
</Struts>

For action login, there is no Action class and only one result. The client request will be forwarded to the login.jsp page when the login action is requested.

For action home, LoginAction is the action class and if execute() method returns SUCCESS the request will be processed by welcome.jsp and for ERROR it will be forwarded to error.jsp page. The namespace="/" is root namespace in Struts.

Now, we can access our application with URL http://localhost:8080/Struts2tutorial/login.action. Notice that URL is ending with .action that is the default suffix for Struts 2 action like it is .do for Struts 1.

The final web project will be with the following folder structure.

final project - eclipse

2.6. Running the web application on Tomcat

After deploying the application to tomcat server, you can take a look at the results below:

2.6.1. LoginPage

Login page

2.6.2. Welocme page

Welcome Page - Struts 2 tutorial

2.6.3. Error Page

Error page - Struts 2 tutorial

3. Download the code project

This was an example of Struts 2 in eclipse.

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

Ima Miri

Ima is a Senior Software Developer in enterprise application design and development. She is experienced in high traffic websites for e-commerce, media and financial services. She is interested in new technologies and innovation area along with technical writing. Her main focus is on web architecture, web technologies, java/j2ee, Open source and mobile development for android.
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
Sergio Madaleno Campos Sebastiao
Sergio Madaleno Campos Sebastiao
6 years ago

Hello!
I did everything as it is in the tutorial but the final result of the webpage presented me the following:
HTTP Status 404 – /struts2tutorial/home.action;
description The requested resource is not available.

what to do?

Vaibhav Pawar
Vaibhav Pawar
4 years ago

Hi,
Please put the struts.xml file under WebContent/WEB-INF/classes instead of putting it into resources.

Back to top button