Skip to content
javahacks.dev
Struts

Struts 1 to 2 Migration Upgrade Step by Step Guide

Migrate a Struts 1 application to Struts 2 in stages: run both side by side, convert actions, forms, validation and tags, and cut over by module.

7 min read
Summarize in AI
Flat illustration of a staircase from one version to the next, with the Gradle, Spring Boot, OpenJDK and Apache Maven logos.

Struts 1 and Struts 2 share a name and a lineage, and almost no code. A migration is a rewrite of the web layer, done in stages. Struts 1 is end of life, so a Struts 1 application is a security risk, and the question is the target. This post covers the move to Struts 2, and migrating to Spring MVC is the alternative route.

What changes

Struts 1Struts 2
Action singleton, execute(mapping, form, request, response)New action per request, execute() returns a String
ActionForm beanProperties on the action (or a model object)
struts-config.xmlstruts.xml
ActionForwardResult names
Validator XML, validate()validate() or <action>-validation.xml, annotations
Struts tags, JSTLStruts 2 tags with OGNL
ActionServletStrutsPrepareAndExecuteFilter

An action in Struts 1 must be thread safe because one instance serves all requests. In Struts 2 an action instance serves one request, which makes fields safe, and the code simpler.

Step 1: put Struts 2 beside Struts 1

XML
<servlet-mapping>
  <servlet-name>action</servlet-name>          <!-- Struts 1 -->
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>*.action</url-pattern>          <!-- Struts 2 -->
</filter-mapping>

Two extensions let both run in one web application. Both jars need to be present and the class names are different, but the Struts 2 filter must not claim the *.do pattern. Plan the order: migrate by module, with links between old and new pages, or move one screen at a time.

Step 2: convert one action

Struts 1:

java
public class SaveCustomerAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest req, HttpServletResponse res) {
        CustomerForm f = (CustomerForm) form;
        service.save(f.getName(), f.getEmail());
        return mapping.findForward("success");
    }
}

Struts 2:

java
public class SaveCustomerAction extends ActionSupport {
    private String name;
    private String email;

    @Override
    public String execute() {
        service.save(name, email);
        return SUCCESS;
    }
    public void setName(String name) { this.name = name; }
    public void setEmail(String email) { this.email = email; }
}
XML
<action name="saveCustomer" class="dev.javahacks.web.SaveCustomerAction">
  <result type="redirectAction">customers</result>
</action>

Request parameters populate the properties through the params interceptor. The form bean disappears, along with its reset logic. For the flow of a request in the new framework, see action request flows.

Step 3: validation and messages

Struts 1 validation in validate() or validation.xml moves to validate() on the action, or to SaveCustomerAction-validation.xml. Use the same messages by turning MessageResources into a package.properties resource bundle. The details of the new validators are in Struts 2 validation.

Step 4: views

Struts 1 <html:text> and <logic:iterate> become <s:textfield> and <s:iterator>. Expressions use OGNL, not JSP EL, and OGNL has a security history, see using OGNL safely. Tiles can be replaced by Tiles 3 with the Struts 2 plugin or by Sitemesh.

Step 5: remove Struts 1

When the last *.do link is gone, delete the servlet mapping, the jar and struts-config.xml. Run the test suite, and scan dependencies for the old transitive libraries.

Generate the first draft of struts.xml from the old config

The mapping from struts-config.xml to struts.xml is regular enough to script, and a script gives you a complete list of actions to work through. This Python script converts action mappings, forwards and global forwards. It handles the common attributes and leaves the rest as a to-do for a person.

convert.pypython
import sys, xml.etree.ElementTree as ET

root = ET.parse(sys.argv[1]).getroot()
print('<struts>')
print('    <package name="default" extends="struts-default">')
print('        <global-results>')
for f in root.iterfind('global-forwards/forward'):
    print(f'            <result name="{f.get("name")}">{f.get("path")}</result>')
print('        </global-results>')
for a in root.iterfind('action-mappings/action'):
    name = a.get('path').lstrip('/')
    print(f'        <action name="{name}" class="{a.get("type")}">')
    for f in a.iterfind('forward'):
        kind = ' type="redirect"' if f.get('redirect') == 'true' else ''
        path = f.get('path').replace('.do', '.action')
        print(f'            <result name="{f.get("name")}"{kind}>{path}</result>')
    if a.get('input'):
        print(f'            <result name="input">{a.get("input")}</result>')
    print('        </action>')
print('    </package>')
print('</struts>')

Run on a sample struts-config.xml with a login action (form bean, validate, input page, two forwards) and a logout action that redirects, it produced:

XML
<struts>
    <package name="default" extends="struts-default">
        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>
        <action name="login" class="com.example.web.LoginAction">
            <result name="success">/welcome.jsp</result>
            <result name="failure">/login.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
        <action name="logout" class="com.example.web.LogoutAction">
            <result name="success" type="redirect">/login.action</result>
        </action>
    </package>
</struts>

Three conversions needed thought. The .do extension became .action, the default in Struts 2, so every link and redirect in JSPs needs the same change. Struts 1's validate="true" and input page became an input result, which Struts 2 returns when validation fails. And a redirect="true" forward became type="redirect". The script cannot know that LoginAction must now extend ActionSupport and return strings instead of ActionForward objects, which is the manual part, covered next. Treat the output as a to-do list: each generated <action> is one conversion task.

Convert one action by hand

Struts 1 actions receive the form and the request and return an ActionForward. Struts 2 actions are objects with properties; the framework fills them from the request and calls execute(), which returns the name of a result.

Struts 1java
public class LoginAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) {
        LoginForm f = (LoginForm) form;
        if (users.authenticate(f.getUsername(), f.getPassword())) {
            request.getSession().setAttribute("user", f.getUsername());
            return mapping.findForward("success");
        }
        return mapping.findForward("failure");
    }
}
Struts 2java
public class LoginAction extends ActionSupport implements SessionAware {

    private String username;
    private String password;
    private Map<String, Object> session;

    @Override
    public String execute() {
        if (users.authenticate(username, password)) {
            session.put("user", username);
            return SUCCESS;
        }
        addActionError(getText("login.failed"));
        return "failure";
    }

    // getters and setters for username and password
    @Override public void setSession(Map<String, Object> session) { this.session = session; }
}

The form bean disappeared: username and password are properties of the action itself, and the params interceptor fills them. The servlet request and response are gone from the signature, and the session arrives through SessionAware instead of request.getSession(). That makes the action testable without a servlet container, because a unit test can construct it, set two properties and call execute().

Migrate validation and messages with the action

Validation moves from validate() on the form bean, or the Validator framework's validation.xml, to the action's own validate() method, to LoginAction-validation.xml, or to annotations. The resource bundle keeps its keys, but the access changes from <bean:message> to getText() and <s:text>. Convert the properties file once, and keep the key names unchanged so JSPs can be migrated page by page without touching the text.

java
@Override
public void validate() {
    if (StringUtils.isBlank(username)) addFieldError("username", getText("login.username.required"));
}

Run both versions together until the last page moves

Struts 1 and Struts 2 can coexist in one web application, because they use different URL extensions (.do and .action) and different filters and servlets. Add the Struts 2 filter mapped to *.action, keep the Struts 1 servlet on *.do, and move one flow at a time, starting with a screen that few users touch. Link between the two while the migration lasts. Remove the Struts 1 servlet and jars only after the last .do reference is gone, which a search of the JSPs, the JavaScript and the configuration files confirms.

Shell
grep -rn '\.do\b' src/main/webapp src/main/resources | grep -v '\.doc' | wc -l

A count of zero, together with an access log that shows no request for a .do URL for a full release cycle, is the signal that the old stack can go.

Decide the order by risk

The order in which actions are converted matters for risk more than for effort. Start with read-only screens, which have no side effects, then simple forms, and leave multi-step wizards and anything that writes money or inventory to the end, when the team knows the new patterns. For each action, keep three artefacts in the pull request: the old and new mapping, a test that calls the new action with representative parameters, and a note of the manual steps a reviewer should repeat in a browser.

Struts 2 has a different security history, so apply the hardening from the start: keep the framework at a current release, restrict the methods that can be invoked by URL, turn off dynamic method invocation, and review OGNL expressions that take user input. Do not copy the permissive defaults that old tutorials show. Finish the migration with a short review of struts.xml for constants that loosen those protections.

Where this does not apply

Do not stop at Struts 2 if the application will live for years. Its framework conventions are not shared by anything newer, and Struts 2 itself needs regular upgrades, see Struts 2 to 6 and 7. The reference is the Struts 1 to 2 migration notes, the Struts 1 retirement notice explains the end of life, and the Struts 2 tutorial walks through the new model.

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.