Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 119 ยท Servlets and JSP

Apache Struts Overview

Understand Apache Struts, the first popular Java MVC framework - Action classes, ActionForm, struts-config.xml, the request flow, Struts 2 interceptors and why Spring MVC replaced it.

Apache Struts is one of the oldest and most influential Java web frameworks. Released in 2000, it was the first widely used implementation of the MVC pattern on top of servlets and JSP: one servlet receives every request, a configuration file maps URLs to small classes called actions, and JSP pages only display results. For about ten years, "Java web development" mostly meant Struts. You will still meet it today in long-lived business systems, so you should be able to read it, understand its vocabulary, and know why most new projects chose something else.

In this lesson you will learn the two generations of Struts (1 and 2), the roles of Action, ActionForm and the configuration file, and how a request travels through the framework. Struts needs a servlet container, which can't run on this page, so the real Struts code is shown read-only. A small runnable program rebuilds the same flow (front controller, mapping, form bean, validation, forward) in plain Java so you can see every step. You should know servlets and JSP first.

Struts 1 reached end of life in 2013 and has known unfixed vulnerabilities. Struts 2 is maintained, but it has had several serious security flaws, most famously an expression-injection bug in 2017 that was used in a large data breach. If you maintain a Struts application, keep it on the latest supported release. For new projects, prefer Spring MVC or Spring Boot.

The idea: one front controller

Before MVC frameworks, each JSP or servlet handled its own request, mixed HTML with SQL, and repeated validation and navigation logic everywhere. Struts introduced a clearer split:

  • Model: your business objects and data access (any plain Java).
  • View: JSP pages (or other templates) that only render.
  • Controller: one framework servlet (or filter) that receives every request, decides which action should run, and chooses which view to show next.
flowchart LR
    B["Browser"] --> FC["Front controller<br/>(ActionServlet / filter)"]
    FC --> M["Mapping<br/>(struts config)"]
    M --> A["Action class"]
    A --> S["Service / DAO"]
    A --> FC
    FC --> V["JSP view"]
    V --> B

Every request enters through one controller. The configuration file, not Java code, decides which action and which view are involved.

Struts 1: Action, ActionForm and struts-config.xml

Struts 1 (2000 to 2013) had three main parts.

An ActionForm is a JavaBean that holds the data of an HTML form. The framework copies the request parameters into its properties and can validate them:

Java
public class LoginForm extends ActionForm {
    private String username;
    private String password;

    // getters and setters ...

    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (username == null || username.isBlank()) {
            errors.add("username", new ActionMessage("error.username.required"));
        }
        return errors;
    }
}

An Action is the controller code for one URL. Its execute method does the work and returns an ActionForward, a logical name for the next page:

Java
public class LoginAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) {
        LoginForm login = (LoginForm) form;
        if (userService.check(login.getUsername(), login.getPassword())) {
            request.getSession().setAttribute("user", login.getUsername());
            return mapping.findForward("success");
        }
        return mapping.findForward("failure");
    }
}

The struts-config.xml file ties it all together: it declares the form beans, maps URLs to actions, and maps logical forward names to real pages:

XML
<struts-config>
  <form-beans>
    <form-bean name="loginForm" type="com.example.LoginForm"/>
  </form-beans>

  <action-mappings>
    <action path="/login" type="com.example.LoginAction"
            name="loginForm" scope="request" validate="true" input="/login.jsp">
      <forward name="success" path="/welcome.jsp"/>
      <forward name="failure" path="/login.jsp"/>
    </action>
  </action-mappings>
</struts-config>

The web.xml registers org.apache.struts.action.ActionServlet for *.do, so /login.do reaches this mapping. JSP pages use Struts tag libraries such as <html:form> and <html:errors/>.

Struts 1's design has well-known costs. Actions and forms must extend framework base classes, so they are hard to test without a servlet container. Actions are shared by all requests, so they must be thread-safe. Every form needs its own ActionForm subclass, even when a plain object would do.

Struts 2: POJO actions and interceptors

Struts 2 (2007, built from the WebWork framework, not an evolution of Struts 1 code) fixed those problems:

  • The controller is a servlet filter (StrutsPrepareAndExecuteFilter).
  • An action is a plain object with properties, created fresh for every request, so it is thread-safe and easy to unit test. The form and the action are the same class.
  • execute() returns a String result name such as "success" or "input".
  • Cross-cutting behavior (parameter binding, validation, file upload, exception handling, security) lives in a stack of interceptors, much like servlet filters or Spring AOP advice.
  • Pages read action properties with OGNL expressions through a value stack.
Java
public class LoginAction extends ActionSupport {
    private String username;
    private String password;

    // getters and setters ...

    @Override
    public String execute() {
        return userService.check(username, password) ? SUCCESS : INPUT;
    }

    @Override
    public void validate() {
        if (username == null || username.isBlank()) {
            addFieldError("username", "Username is required");
        }
    }
}
XML
<struts>
  <package name="default" extends="struts-default">
    <action name="login" class="com.example.LoginAction">
      <result name="success">/welcome.jsp</result>
      <result name="input">/login.jsp</result>
    </action>
  </package>
</struts>

In a Struts 2 JSP you write <s:form action="login"> <s:textfield name="username"/> <s:fielderror/> </s:form> and display values with <s:property value="username"/>. Annotations (@Action, @Result) can replace struts.xml. Current releases use the Jakarta EE namespace (Struts 7), while Struts 6 still uses javax.servlet, the same split described in Jakarta EE Overview.

A request through Struts, step by step

  1. The browser requests /login.do (Struts 1) or /login.action (Struts 2).
  2. The front controller looks the path up in the configuration.
  3. The framework creates the form bean (or the Struts 2 action) and copies request parameters into its properties.
  4. If validation is on, errors send the user back to the input page, and the action never runs.
  5. The action runs and returns a logical result name.
  6. The controller maps the name to a page and forwards to it.
  7. The JSP renders the response from data the action left in the request or on the value stack.

A miniature Struts you can run

The program below is not Struts. It copies the structure: a mapping table (the "config file"), a form bean filled from parameters through reflection, validation that returns to the input page, an action that returns a logical name, and a front controller that ties them together. Change the parameters at the bottom to see each branch.

Java A tiny front controller with mappings, form beans and forwards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The structure is the lesson: the controller knows nothing about login, the action knows nothing about JSP file names, and the "config" connects them. That separation is what made Struts a step forward in 2000.

Interceptors: the Struts 2 pipeline

In Struts 2, the framework wraps every action in an interceptor stack. Each interceptor can run code before the action, call invocation.invoke() to continue, and run code after it. The program below models a stack with a timer, a parameters step, validation and an exception handler. It is the same chain-of-responsibility idea as filters and AOP advice.

Java An interceptor stack around an action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why Spring MVC replaced Struts

Struts did not fail because MVC was wrong; it was overtaken because other frameworks built the same idea with fewer constraints.

Topic Struts 1 Struts 2 Spring MVC
Controller class Must extend Action POJO, one instance per request POJO method with annotations
Form data One ActionForm subclass per form The action itself Any object (@ModelAttribute)
Dependency injection None built in Plugins Core of the framework
Configuration struts-config.xml struts.xml or annotations Annotations and Java config
Security record End of life since 2013 Several serious CVEs Regularly patched, large team
Ecosystem Small Moderate Security, Data, Boot, Cloud

Spring MVC also lives inside a framework that already provides dependency injection, transactions, data access and security, so you do not assemble those pieces yourself. Compare the same login screen in Spring MVC and the full servlet, JSP and JDBC login project.

If you inherit a Struts application, a common path is: upgrade to the latest Struts 2 release, remove OGNL features you do not use, add tests around actions, and then move screens to Spring MVC one URL at a time, since both can run side by side in the same WAR.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Struts 1, what does an Action's execute method return so the controller can pick the next page?

    Struts 1 actions return an ActionForward (found with mapping.findForward). The real page path lives in struts-config.xml, so Java code never contains JSP file names.
  2. 2. What is the main reason Struts 2 actions are easier to test and thread-safe compared with Struts 1 actions?

    A Struts 2 action instance belongs to a single request, so it holds request state in fields and needs no synchronization, and it can be created in a unit test with new.
  3. 3. In Struts 2, which feature handles cross-cutting work such as validation, parameter binding and exception handling around an action?

    Interceptors wrap the action like filters wrap a servlet. Each can run code before and after the action, or stop the chain and return a result.
  4. 4. Why should you be careful about running an old Struts version?

    Unpatched Struts versions have been exploited in real attacks. Keeping up with releases is essential, and new projects usually pick a better maintained framework.

Summary

  • Struts is an early Java MVC framework: one front controller maps URLs to actions and actions to views through a configuration file.
  • Struts 1 used ActionServlet, Action, ActionForm and struts-config.xml; it has been end of life since 2013.
  • Struts 2 uses a servlet filter, POJO actions that return string results, interceptor stacks, OGNL and struts.xml or annotations.
  • A request is mapped, bound into a form or action, validated, executed, and then forwarded to a view by logical name.
  • Spring MVC replaced Struts in most new projects because of simpler controllers, built-in dependency injection, a wider ecosystem and a better security record.
  • Legacy Struts apps should stay patched and can be migrated page by page, as both frameworks can live in one WAR.

Next: JavaServer Faces (JSF) Basics shows the component-based alternative to this request-based style of web framework.