Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Started With Apache Struts 2

DZone's Guide to

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.

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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>

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
java ee ,maven ,struts 2 ,eclilpse

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}