Visit Sponsor

Written by 1:17 pm Core Java

Struts2 Login Application Tutorial – Complete Setup and Example

Building a login feature is one of the most fundamental tasks when developing web applications with Struts2. This tutorial walks you through creating a login application using Struts2 from scratch — including project setup, configuration, form processing, validation, and session handling.

You will learn how Struts2 handles requests, binds form parameters to action properties, performs validation, and navigates to views using results.

Overview – How Struts2 Works

Struts2 uses the MVC (Model-View-Controller) pattern:

  • Controller: Intercepts requests via FilterDispatcher (or StrutsPrepareAndExecuteFilter)
  • Model: POJOs bound to form input
  • View: JSP pages rendered with Struts2 tags
  • Action: Handles business logic and returns result strings

Struts2 interceptors handle request preparation, parameter binding, validation, and result invocation.

Project Setup

Required Libraries

You can bootstrap a Struts2 project using Maven or manually place the required JARs. When using Maven, include:

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

Use the latest stable Struts2 version available in Maven Central.

Web Descriptor (web.xml)

Configure the Struts2 filter to handle requests:

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

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

This filter intercepts all incoming requests and dispatches them through the Struts2 framework.

Create the Login Form (JSP)

login.jsp

Place this JSP under the web content folder:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <s:form action="login">
        <s:textfield name="username" label="Username" />
        <s:password name="password" label="Password" />
        <s:submit value="Login" />
    </s:form>

    <s:if test="hasActionErrors()">
        <ul>
            <s:actionerror />
        </ul>
    </s:if>
</body>
</html>

This form submits to the login action with username and password fields.

Define the LoginAction

LoginAction.java

Create an action class with getters and setters for form parameters:

public class LoginAction extends ActionSupport {

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

    @Override
    public String execute() {
        if ("admin".equals(username) && "password123".equals(password)) {
            return SUCCESS;
        } else {
            addActionError("Invalid username or password");
            return INPUT;
        }
    }
}

The execute() method checks credentials and returns either SUCCESS or INPUT (to redisplay the login form on failure).

Map the Action in struts.xml

struts.xml

Create or update your Struts2 configuration:

<struts>
    <package name="default" namespace="/" extends="struts-default">

        <action name="login" class="com.javatechig.LoginAction">
            <result name="success">welcome.jsp</result>
            <result name="input">login.jsp</result>
        </action>

    </package>
</struts>

This defines the login action with two possible results: success and input.

Add the Welcome Page

welcome.jsp

This page displays after successful login:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Welcome</title></head>
<body>
    <h2>Welcome, <s:property value="username" />!</h2>
    <s:form action="logout">
        <s:submit value="Logout" />
    </s:form>
</body>
</html>

Parameters from LoginAction are automatically available in the view.

Enabling Validation (Optional)

Struts2 supports annotation or XML validation.

Using XML Validator

Create a file named LoginAction-validation.xml next to your action class:

<validators>
    <field name="username">
        <fieldvalidator type="requiredstring">
            <message>Username is required</message>
        </fieldvalidator>
    </field>
    <field name="password">
        <fieldvalidator type="requiredstring">
            <message>Password is required</message>
        </fieldvalidator>
    </field>
</validators>

Struts2 will invoke this validator before execute() and return input on validation errors.

Session Management

After a successful login, you may want to store the user in a session. Modify the action:

Map<String, Object> session = ActionContext.getContext().getSession();
session.put("USER", username);

Then in JSP:

<s:property value="#session.USER" />

Use the session judiciously and clear it on logout.

Strongly Typed Tags and UI

Struts2 tag library helps to build forms, property displays, and error messages without manual HTML.

Examples:

  • <s:form> for forms
  • <s:textfield> and <s:password> for inputs
  • <s:submit> for submit button
  • <s:actionerror> to display action errors

These tags reduce boilerplate and integrate with the Struts2 type converters and interceptors.

Best Practices (Senior Engineering Insight)

From extensive enterprise experience:

  • Avoid storing plain passwords — use hashing & secure credential validation
  • Use validation interceptors instead of manual checks where possible
  • Encapsulate business logic outside actions (service layer)
  • Namespace your actions for modular modules
  • Use site-wide templates (tiles or layouts) for consistent UI

These practices lead to maintainable and secure Struts2 applications.

Common Issues and Fixes

Login does not submit:
✔ Check that the form action matches the action name in struts.xml

Validation not triggered:
✔ Ensure validator config matches action class name (ActionClass-validation.xml)

Session values not available in JSP:
✔ Verify session interceptor is enabled (default stack includes it)

Summary

This tutorial showed how to build a login application using Struts2, including:

  • Project and filter setup
  • Login form creation
  • Struts2 action with business logic
  • Result mapping for success and failure
  • Optional validation rules
  • Session management for logged-in users

Struts2 simplifies request handling and form processing using conventions and a flexible interceptor stack. With proper architecture, you can extend this login pattern into a full authentication module.

Visited 5 times, 1 visit(s) today
Close