Skip to content
javahacks.dev
Struts

Struts 2 Tutorial for Beginners With Maven and a Login Form

Build a small Struts 2 web application with Maven, a login form, an action class and a struts.xml mapping, and run it on a servlet container.

6 min read
Summarize in AI
Flat illustration of a request passing through a servlet container, with the Apache Maven, Spring, NGINX and Apache Tomcat logos.

This tutorial builds a login form in Struts 2 from an empty Maven project. It is for someone who has been handed a Struts codebase and wants to see the whole thing once. It uses a supported Struts 6 release and a recent JDK. Do not use an old Struts 2 version for a real project, since many old releases have serious security flaws; the reasons are in hardening Struts 2. The flow you build here is described in what Struts 2 is.

Create the project

pom.xmlXML
<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>6.7.4</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<properties>
    <maven.compiler.release>17</maven.compiler.release>
    <failOnMissingWebXml>false</failOnMissingWebXml>
</properties>

Check the Struts download page for the current Struts 6 release and its servlet requirements before copying a version number; the Struts 7 line moved to the Jakarta namespace.

Register the filter

src/main/webapp/WEB-INF/web.xmlXML
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="4.0">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Write the action

src/main/java/dev/javahacks/web/LoginAction.javajava
package dev.javahacks.web;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    private String username;
    private String password;

    @Override
    public String execute() {
        if ("admin".equals(username) && "change-me".equals(password)) {
            return SUCCESS;
        }
        addActionError("Wrong username or password");
        return INPUT;
    }

    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; }
}

The hard-coded credentials are for the tutorial only. A real application checks a hashed password in a service.

Map it in struts.xml

src/main/resources/struts.xmlXML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 6.0//EN"
        "https://struts.apache.org/dtds/struts-6.0.dtd">
<struts>
    <package name="default" extends="struts-default">
        <action name="login" class="dev.javahacks.web.LoginAction">
            <result name="success">/welcome.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
    </package>
</struts>

If you forget the input result you will meet the missing result error.

Write the pages

src/main/webapp/login.jspXML
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
    <s:actionerror />
    <s:form action="login">
        <s:textfield name="username" label="Username" />
        <s:password name="password" label="Password" />
        <s:submit value="Log in" />
    </s:form>
</body>
</html>
src/main/webapp/welcome.jspXML
<%@ taglib prefix="s" uri="/struts-tags" %>
<html><body><h1>Welcome, <s:property value="username" /></h1></body></html>

<s:property> escapes output by default. Do not turn escaping off for user-supplied values.

Run it

Shell
./mvnw package

Copy the WAR to Tomcat's webapps directory and open http://localhost:8080/<context>/login.jsp. Submit the correct credentials and you reach the welcome page; submit wrong ones and the form returns with the error. The .action suffix is added by the <s:form action="login"> tag.

Two errors you will meet first

If the form posts and the page is blank, the action returned a code with no matching result: that is the input case in the missing result error. If every request returns a 404, the filter mapping is missing or the struts.xml file is not on the classpath; check that it sits in src/main/resources so it lands in WEB-INF/classes. If the application starts and an old tutorial's tag library import fails, check that you are using the /struts-tags URI shown above and a Struts release that matches your servlet API.

What actually happens on a request

Walking one request through the framework makes every configuration file in the tutorial make sense. The browser sends POST /login.action. The container hands it to StrutsPrepareAndExecuteFilter, which asks the configuration which action is mapped to login. Struts builds an interceptor stack around that action, and each interceptor does a job before and after it: one populates your action's fields from the request parameters, one runs validation, one handles exceptions. Then your execute() method runs and returns a string such as success or input. That string selects a <result> in struts.xml, which names the page to render. Everything you configure is one of these steps.

This is also how you debug it. If a field is not filled, the parameters interceptor did not find a setter with the right name and type. If validation seems ignored, the action's result name was not input, which is where Struts sends a request that failed validation. If the wrong page appears, compare the string your action returned with the result names in the mapping.

Validation and error messages

The tutorial's login form is a good place to add validation, since it shows the model. Put a validate() method on the action that calls addFieldError("username", "Username is required") when a field is empty, and Struts returns input automatically, showing the messages next to the fields through the <s:fielderror> tag or the form tags' built-in support. For rules that repeat across actions, an XML validation file named LoginAction-validation.xml next to the class declares them without code. Keep the real authentication check in execute(), since validation checks shape and not truth.

Security notes for a beginner project

Struts has a long history of serious vulnerabilities, most of them in OGNL expression handling, and the lesson is that the version matters more than anything else you configure. Use the latest 6.x release, subscribe to the security bulletins, and never build an OGNL expression from user input. Store passwords hashed with a modern algorithm such as bcrypt or Argon2, not in plain text as a tutorial table might. Regenerate the session id after login. A tutorial login is a starting point, and a real one needs those three things before a user touches it.

Where to go next

Once the form works, add a second action that reads from a database through plain JDBC or a small DAO, display the result in a list with <s:iterator>, and write an integration test with the Struts JUnit plugin. After that, compare the experience with a modern alternative in the same series, to judge whether Struts fits what you are building.

Packaging and running it

The project builds as a WAR with mvn package, and the result drops into Tomcat's webapps directory. For quick local runs, the Jetty Maven plugin starts the application with mvn jetty:run, with no installation of a server, and reloads classes when you recompile. Check the browser at http://localhost:8080/login.action, and keep one eye on the console, where Struts logs the mapping it loaded. If a page returns 404, the console usually shows that the action was not found because the struts.xml file is not on the classpath, which in a Maven project means it sits in src/main/resources and not next to the Java files.

A note on the file layout

Keep actions, models and services in separate packages from the first day: actions, model and service. A tutorial that puts everything in one package works for a login form and turns into a tangle when the third screen arrives. The action should only translate between the request and a service call, and the service holds the rules.

Struts today

Struts 2 is maintained, and many companies still run it, which is the main reason to learn it. For a new project most teams pick Spring MVC or a component framework instead, so treat this tutorial as the way to read and maintain an existing application with confidence.

Where this tutorial stops

Real applications add validation (validating input), interceptor stacks and a layout. The Struts getting started guide walks through a larger example, and a project of any size should read the security guide first.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.