DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Getting Started With Apache Struts 2

Getting Started With Apache Struts 2

Let's learn how to create a running web application using Apache Struts 2 and a set of practical use cases.

Ba Mamadou Lamine user avatar by
Ba Mamadou Lamine
·
Dec. 11, 16 · Web Dev Zone · Opinion
Like (4)
Save
Tweet
7.01K Views

Join the DZone community and get the full member experience.

Join For Free

This article is the first in a series to discover the possibilities of the Model-View-Controller framework that is Apache Struts 2. In this part, we will cover the basics of creating a running web application and through a set of practical use cases, you will gain a complete mastery of all of its concepts to avoid any misunderstanding. 

Creating a Project

Creating an Apache Struts 2 project using Eclipse is really straightforward and involves creating a dynamic web project with an auto-generated web.xml, which you later convert to an Apache Maven project if you are not using Gradle. You will add the following dependencies in your pom.xml if you choose to run on its 2.3.16 version.

pom.xml

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.3.16</version>
    </dependency>
</dependencies>

Creating a Running Web Application

Having the Apache Struts 2 jars and its dependencies available on your classpath does not mean that you have a preconfigured web application ready to be displayed at runtime. To get things working, we still have to declare the filter that is responsible to load its configurations and to initialize the plugins. And later, we will see how to use Apache Tiles in order to set a common look and feel across all of our web pages with a template.

web.xml

<web-app>

    <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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

</web-app>

The Servlet 3 API has also opened the door to make the web.xml optional through a programmatic approach and with the use of a ServletContextListener, one can register the filter at startup.

StartupListener.java

@WebListener
public class StartupListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        FilterRegistration struts2 = event.getServletContext().addFilter("struts2",
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.class);
        struts2.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,
        DispatcherType.FORWARD),true, "/*");
        struts2.setInitParameter("config","struts-default.xml,struts-plugin.xml,struts.xml");
    }

}

Running Your Web Application

Once the configuration step is done, you can run your web application and access its root context to display its index page and the handling is done by the web container. But if you want it to be managed by Apache Struts to do something before the display, then you will have to create a configuration file stored at the root of your classpath to declare an action with a result of dispatcher type which is the default type and can be omitted.

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="root" namespace="/" extends="struts-default">
        <action name="" class="WelcomeAction">
            <result name="success" type="dispatcher">index.jsp</result>
        </action>
    </package>
</struts>

WelcomeAction.java

public class WelcomeAction extends ActionSupport {

    private String message;

    public String execute() {
        message = "Welcome to Apache Struts 2";
        return SUCCESS;
    }

    public String getMessage() 
        return message;
    }

}

web.xml

<web-app>
    <welcome-file-list>
        <welcome-file>index.action</welcome-file>
    </welcome-file-list>
</web-app>

The same can be achieved programmatically for no web.xml and of course, everything can be automated for ease and for something more powerful.

WelcomeServlet.java

@WebServlet("/index.html")
public class WelcomeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)
    throws ServletException, IOException {
        request.getRequestDispatcher("index").forward(request, response);
    }

}

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="root" namespace="/" extends="struts-default">

        <action name="index" class="WelcomeAction">

            <result>index.jsp</result>

        </action>

    </package>

</struts>

index.jsp

<!DOCTYPE html>
<html>
  <head>
    <title>Apache Struts 2</title>
    <style>
      h1 {
          margin-top:17%;
          background-image : url("images/struts-logo.jpg");
          background-repeat : no-repeat;
          background-position : 35% 50%;
          padding-left : 50px;
          line-height : 55px;
      }

    </style>
  </head>
  <body>
    <h1 align="center">${message}</h1>
  </body>
</html>
Apache Struts Apache Struts 2 Web application

Published at DZone with permission of Ba Mamadou Lamine. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What's the Difference Between Static Class vs. Singleton Patterns in C#?
  • How to Build Microservices With Node.js
  • Five Tips to Fasten Your Skewed Joins in Apache Spark
  • Event-Driven Microservices?

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo