Skip to content
javahacks.dev
Struts

Migrate Struts to Spring MVC Incrementally Without a Rewrite

Move a Struts application to Spring MVC one URL at a time: add Spring beside Struts, route by path, port actions, share services and retire Struts.

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

A rewrite of a large web application freezes features for months. An incremental move keeps shipping and removes risk. The idea is to let Spring MVC take over URL by URL. The reason for moving is laid out in Struts 2 vs Spring MVC.

Step 1: put Spring in the web application

Add Spring and a context for it. If Struts already uses the Spring plugin, the context exists, see Struts with Spring. Then register the dispatcher:

XML
<servlet>
  <servlet-name>mvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:mvc-context.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>mvc</servlet-name>
  <url-pattern>/v2/*</url-pattern>
</servlet-mapping>

Struts keeps /* or *.action, and the new screens live under /v2/. Later, when most pages have moved, invert it: Spring takes /, and the Struts filter covers only what remains. Servlet mapping precedence means the more specific pattern wins, so check each URL in a test.

Step 2: move services first

Business logic should not depend on the web layer. If it sits in actions, extract it into service classes that take plain arguments. Register them as Spring beans. Both Struts actions and Spring controllers then call the same code, so each migrated screen is only a thin web change. Persistence stays as it is.

Step 3: port one action

Struts:

java
public class CustomerSearchAction extends ActionSupport {
    private String query;
    private List<Customer> results;

    public String execute() {
        results = customerService.search(query);
        return SUCCESS;
    }
    // getters and setters
}

Spring MVC:

java
@Controller
@RequestMapping("/v2/customers")
class CustomerController {
    private final CustomerService customers;
    CustomerController(CustomerService customers) { this.customers = customers; }

    @GetMapping("/search")
    String search(@RequestParam(defaultValue = "") String query, Model model) {
        model.addAttribute("results", customers.search(query));
        return "customers/search";
    }
}

The request parameter binding, the model and the view name replace the action's properties and result names. For JSON, return an object from a @RestController, as in a REST controller.

Step 4: forms and validation

A Struts form with validate() becomes a request record with Bean Validation, as in validating request bodies, and error messages move to a MessageSource. A Struts interceptor that does cross-cutting work, like auditing or authentication, becomes a Spring HandlerInterceptor or a servlet filter, see the request path.

Step 5: views

Keep the JSPs, replacing <s:textfield> with <form:input> from the Spring form tag library, and OGNL expressions with JSTL and EL. A shared layout can be preserved with Tiles or Sitemesh, and later swapped for Thymeleaf. Cutting JSP for Thymeleaf is its own step, not part of this one.

Step 6: remove Struts

When no Struts URL is left, delete the filter and mappings, struts.xml and the Struts jars. Run a dependency check, because Struts brought OGNL, FreeMarker and XWork with it.

Keep it safe

  • Keep a redirect list so old URLs reach the new ones.
  • Run the same acceptance tests against both versions of a screen.
  • Migrate screens with the most changes first, as that is where the new framework pays back.

Take stock before the first move

An incremental migration needs a list. This script reads struts.xml and prints each action with its class and results, so you can sort them by risk and size. It runs on the sample file produced in the Struts 1 to 2 post.

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

root = ET.parse(sys.argv[1]).getroot()
for pkg in root.iterfind('package'):
    for a in pkg.iterfind('action'):
        results = ', '.join(f"{r.get('name')}->{(r.text or '').strip()}" for r in a.iterfind('result'))
        print(f"{a.get('name'):12} {a.get('class'):40} {results}")

Add three columns by hand: how often the action is hit (from the access log), how many pages it renders, and how much business logic lives in the action itself. The best first candidates are actions that are rarely used, render one page and delegate to a service. The last to move are the high-traffic flows with logic inside the action class, which you first extract into a service while still on Struts, so the move to Spring MVC is a thin change.

Run Spring MVC beside Struts

Both frameworks can share a web application if their URL spaces do not overlap. Map the Spring DispatcherServlet to a distinct prefix, and keep the Struts filter on its existing mapping. A request goes to whichever framework owns its path.

src/main/webapp/WEB-INF/web.xmlXML
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/v2/*</url-pattern>
</servlet-mapping>

A reverse proxy can then move traffic gradually: send /login.action to the Struts path and /v2/login to Spring, and change the mapping per route as each page is ported. When a page moves, redirect the old URL to the new one with a 301 so bookmarks and search engines follow, and keep the redirect until the access log shows the old URL is no longer requested.

Port one action

The port keeps the service call and replaces the framework plumbing. The Struts action from before:

java
public class OrderAction extends ActionSupport {
    private long id;
    private Order order;

    public String show() {
        order = orders.find(id);
        return order == null ? "notfound" : SUCCESS;
    }
}

becomes a controller whose method takes parameters directly and returns a view name:

java
@Controller
@RequestMapping("/v2/orders")
class OrderController {

    private final OrderService orders;

    OrderController(OrderService orders) { this.orders = orders; }

    @GetMapping("/{id}")
    String show(@PathVariable long id, Model model) {
        Order order = orders.find(id);
        if (order == null) return "orders/notfound";
        model.addAttribute("order", order);
        return "orders/show";
    }
}

Test the new endpoint beside the old one with the same data and compare the pages. A MockMvc test documents the behaviour, and a side-by-side HTML comparison on a staging copy shows the visible differences.

java
mvc.perform(get("/v2/orders/42"))
   .andExpect(status().isOk())
   .andExpect(model().attribute("order", hasProperty("id", is(42L))))
   .andExpect(view().name("orders/show"));

Share the services, not the actions

Services written as plain classes can be used by both frameworks while the migration runs. Register them as Spring beans and let Struts actions obtain them through the Struts 2 Spring plugin, so a service bug is fixed once. Do not let new Spring code call Struts actions or depend on Struts classes. The dependency should point one way, from the old toward the shared services, so removing Struts later deletes code without changing the new side.

Keep the shared pieces honest during the long middle

The long middle of an incremental migration is the period in which both frameworks serve users. Two dangers show up there. The first is behaviour drift between the old page and its replacement: a rounding rule, a date format, a permission check that the Struts action performed in a base class and the new controller forgot. Capture those as tests against the old behaviour before porting, and run the same tests against the new endpoint. The second is session state. Struts stores form beans in the HTTP session by default, and Spring MVC code usually does not, so a user who moves between a Struts page and a Spring page needs the data both rely on in a shared, explicit place, such as a session attribute with a documented name. Write that list down and shrink it as pages move.

Where this does not apply

If the application has a handful of screens and no future, a Struts upgrade is cheaper, see Struts 2 to 6 and 7. The target framework is described in the Spring MVC REST guide. The reference is the Spring MVC documentation, and the strangler fig pattern describes the approach.

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.