Struts 2 Login Example

Site Admin · 11 Sep 2026 · 2 views

The Login Action

An action is a POJO with properties and an execute() method that returns a result code:

public class LoginAction {
    private String username;
    private String password;

    public String execute() {
        if ("admin".equals(username) && "secret".equals(password)) {
            return "success";
        }
        return "error";
    }
    // getters/setters for username and password
}

The params interceptor fills username and password from the form automatically.

struts.xml Mapping

<action name="login" class="com.example.LoginAction">
    <result name="success">/welcome.jsp</result>
    <result name="error">/login.jsp?error=true</result>
</action>

The Login Form

<s:form action="login">
    <s:textfield name="username" label="Username"/>
    <s:password name="password" label="Password"/>
    <s:submit value="Login"/>
</s:form>

Struts tags need the taglib line in the JSP header.

Struts 2 login form

Output

Valid credentials redirect to the welcome page; wrong ones show an error.

Struts 2 login result output

Key Points

  • Action properties are populated automatically from form fields.
  • Return strings decide which result view renders.
  • Validate with the params + validation + workflow stack in production.
Share this post:

Comments (0)

Please login or register to comment.