October 21, 2026

Everything Is Static: Taking a Java Web App to Rust

Reading the Java is the easy part. The hard part is everything the JVM and the servlet container do for you without saying so: static fields every user shares, null printed as a word, stack traces sent to the browser, and text squeezed into ISO-8859-1. Here's how we found those rules in a real JSP and Servlet app, moved it to Rust behind nginx one group of pages at a time, and proved every response matches byte for byte.

Everything Is Static: Taking a Java Web App to Rust

Java runs a large share of the world's business software, and modern Java is a good platform. The JIT is excellent, virtual threads made blocking code cheap again, and records and pattern matching cut a lot of boilerplate. If your Java service works and your team likes it, there's no rule that says you have to leave.

But some teams have good reasons to move part of it. A service needs hundreds of megabytes of heap to answer a few requests a second. Containers take seconds to start, which hurts when they scale up and down all day. Garbage collection pauses show up in the slowest one percent of requests. Or the team is tired of NullPointerException in production. Rust is a strong choice for those parts. It starts in milliseconds, it uses little memory, it has no garbage collector, and the compiler won't let a value be null by accident.

Reading the Java turned out to be the easy part. What's hard is everything the JVM and the servlet container do without anyone writing it down. A static field is shared by every user of the server. A missing value prints as the word null. A bad number becomes a stack trace in the browser. A euro sign turns into a question mark. Your users and clients depend on all of it, whether you meant them to or not. Rust makes you write each of those rules down, so most of a migration is finding them.

The example: every snippet in this post comes from a real app you can run: FlyAway, a flight-booking site built with JSP pages and Servlets on Tomcat with MySQL, and our Rust rewrite of it with axum, sqlx and askama. It's five Java classes and eleven JSP pages, 1,014 lines: search for a flight, pick one, enter passenger and card details, and an admin dashboard. Both versions, the recorded traffic and the nginx setup are at cobuild-tech/migratex-examples. Where Spring changes the picture, we say so.

Before You Start

Before you start: list every servlet, JSP page, web.xml mapping, filter, static field and Maven dependency. Write down what Java and Tomcat do for you, such as one static field shared by everyone, null printed as the word null, and a euro sign turned into a question mark. Then record real requests and responses, restarting the server between sessions

Should you move at all?

Be specific about why. "Java is slow" isn't a good reason. Once it's warmed up, the JVM is fast, and most web requests spend their time waiting on the database anyway. Good reasons look more like: this service needs eight replicas just to hold its heap. Or our functions start too slowly to scale to zero. Or the slowest requests are all garbage collection pauses. Or we keep shipping null pointer bugs that the compiler could have caught.

Then move only those parts. Rewriting a whole Java system in one go is how projects stall for a year. With a proxy in front, you can move a piece and leave everything else exactly where it is.

Make a list of everything that runs

  • URLs and what serves them: web.xml mappings, @WebServlet annotations, JSP pages, Spring controllers. Your access logs tell you which ones matter.
  • Filters and listeners, which run on every request or at startup without being called from anywhere.
  • State held in memory: static fields, HttpSession attributes, caches, and in Spring, fields on singleton beans. More on this below, because it decides how you move.
  • The data layer: JDBC, JPA entities and their mappings, and the connection pool, which may be configured in the server rather than the app (context.xml, JNDI).
  • Scheduled jobs and queues: @Scheduled, Quartz, JMS listeners. These are often a good place to start.
  • Server and JVM settings that change behaviour: Tomcat's connector encoding, -Duser.timezone, -Dfile.encoding, heap size.
  • Maven or Gradle dependencies, and what each one would become in Rust. Some won't be used at all. FlyAway's pom.xml pulls in Hibernate, and nothing calls it.

Our example is small: three servlets, eleven JSP pages, two model classes, no framework. Small doesn't mean simple, though. Every rule below came out of those 1,014 lines.

Find the state first

Here's the whole of model/Search.java, which holds the visitor's search:

public abstract class Search {
    public static String date;
    public static String day;
    public static String source;
    public static String destination;
    public static int persons;

    public static String getQuery() {
        return "SELECT * FROM flight WHERE source = '"+source+"' AND destination='"+destination+"' AND days like '%"+day+"%'";
    }
}

Every field is static, so there is one search for the whole server. When a second visitor searches, the first one's results change. Booking is the same, card number included. So is the admin login: Login.isLoggedIn is one static boolean. Once the admin logs in, anyone can open the dashboard. Anyone who fails to log in, or just opens the login page, logs the admin out.

This is easy to dismiss as a beginner's mistake. But it's the same bug as a field on a Spring @Controller or @Service, which are singletons by default: one instance, shared by every request. Look for both. Wherever state lives in memory, it will decide how you move, as you'll see below.

Write down what Java does for you

Then look for the rules nobody wrote. We found every one of these by running the original:

What Java and Tomcat doWhat we sawWhat it means for Rust
Share static fields across all requestsBob's search replaces Ann's. A failed login logs the admin outState goes in a session, or in one app that owns it
Print a null String as nullBefore any search: "Showing available flights from null to null"Option<String>, and decide what None shows
Write <%= %> values as they are<b> in a search shows up as bold text. So would a scriptEscape by default. Templates like askama do
Accept more than you'd think in Integer.parseInt+3, 007 and ٣ (Arabic-Indic 3) are all 3. " 1" is an errorCopy the rule while you need to match, then narrow it
Accept more than you'd think in LocalDate.parse+12026-10-19 is a date. 2026-02-30 is a stack traceThe same
Show uncaught exceptions to the userA missing field: HTTP 500 with the exception, the class, the line number and the Tomcat versionErrors are part of the contract until you change them on purpose
Read forms and write pages as ISO-8859-1€ in a search shows as ?Match the bytes, not just the characters

Record real traffic before you change anything

Save a sample of real requests and the responses Java sent back, for everything you plan to move. Mask the personal data, but keep the strange ones. These golden pairs are your spec. The Rust version is correct when it gives the same response to the same request.

Our example has no production traffic, so we wrote it: 13 scripted sessions, 174 requests, covering every page, every servlet, wrong methods, missing fields, odd numbers and dates, injected SQL and HTML, and text outside ASCII. We ran it on the server the project was built for: Tomcat 9.0.44 on Java 8, in Docker. Because the state is in static fields, the script restarts Tomcat before each session, or one session's search would leak into the next. Here's part of what Tomcat sent for persons=abc:

HTTP/1.1 500
Content-Type: text/html;charset=utf-8

...<p><b>Message</b> For input string: &quot;abc&quot;</p>...
<pre>java.lang.NumberFormatException: For input string: &quot;abc&quot;
	java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	java.lang.Integer.parseInt(Integer.java:580)
	java.lang.Integer.parseInt(Integer.java:615)
	servlets.SearchServlet.service(SearchServlet.java:19)
...
<h3>Apache Tomcat/9.0.44</h3>

The stack trace, the line numbers and the server version, sent to anyone who changes a URL. If a monitoring check somewhere looks for NumberFormatException in the page, that's its error handling. That's why the recordings come before any decisions.

Running Java and Rust Together

Running Java and Rust together: group the URLs by the static fields they share. nginx sends each group to either the Rust service or Java, and both use the same MySQL database. Groups move to Rust one at a time until Java has none left

As with our other migrations, we move one piece at a time while the rest keeps running. Martin Fowler calls this the strangler fig pattern. For a web app the tool is the proxy you probably already have. But what counts as one piece depends on the state.

One state, one owner

In our PHP migration, every request read and wrote the database, so routes could move one at a time. FlyAway keeps its state in the JVM's memory. If /search is served by Rust and search-results.jsp by Java, Java never sees the search. So the URLs move in groups that share state. FlyAway has three: pages with no state, the booking flow (Search and Booking), and the admin pages (Login). In nginx:

upstream java { server java:8080; }
upstream rust { server rust:8080; }

server {
    # booking: moved
    location = /search              { proxy_pass http://rust; }
    location = /search-results.jsp  { proxy_pass http://rust; }
    location = /booking-details.jsp { proxy_pass http://rust; }
    location = /payment.jsp         { proxy_pass http://rust; }
    location = /thank-you.jsp       { proxy_pass http://rust; }

    # admin: still on Java
    location = /login               { proxy_pass http://java; }
    location = /admin-dashboard.jsp { proxy_pass http://java; }
    ...
}

Each group belongs to exactly one side, and switching back is a few lines and a reload. In a real system, the groups are usually bigger, and the honest answer is often to move the state out first. Put sessions in Redis with Spring Session, or in a table, as its own change, before anything moves. Then any URL can move on its own.

Talk to Tomcat the way browsers did

Putting nginx in front changed two of Java's answers. nginx talks to the server it proxies with HTTP/1.0 by default. Over HTTP/1.0, Tomcat sends a redirect with the full URL instead of a path, and answers a GET to a POST-only servlet with 400 instead of 405. Two lines fix it:

proxy_http_version 1.1;
proxy_set_header Host $http_host;

We found that by recording through nginx and comparing. With those two lines, all 174 recordings match through the proxy, except a TRACE request that nginx refuses itself. Check your proxy against the recordings too, not just the new code.

Share the database, carefully

Both sides read the same flight table. FlyAway only reads, which makes this part easy, but check how Java connects anyway. Each JSP page opens its own connection with DriverManager.getConnection and never closes it. That's a leak, and the Rust side uses a pool instead. The character set is fine here: Connector/J 8 and sqlx both connect as utf8mb4. Check yours. In our PHP migration, a connection with no charset meant the two apps stored the same name differently.

From Objects to Types

From objects to types: in compat mode, null becomes Option, Integer.parseInt and exceptions are written down with their stack frames, and the page text is read from the original JSP files. In the default mode, the static fields become a session for each visitor, the price comes from the table, SQL values are bound, and output is escaped. For Spring, annotations become ordinary code

Java gives every value a type, so this should be the easy part. It isn't, because the types allow null everywhere, and the behaviour lives in the libraries. A Rust port can't reproduce Java while both are live unless it reproduces those too. So the port has two modes, as our COBOL and PHP ports did:

  • Compat mode (FLYAWAY_COMPAT=1) answers exactly as Tomcat did, stack traces included. It runs while both sides serve traffic, and it's what the golden tests check.
  • The default mode fixes the bugs. Each fix has a comment saying what Java did, and its own test.

Write the JVM down

A Java String that may be null becomes Option<String>, and None prints as null, because that's what Java printed. The servlet becomes a function over the same fields, in the same order. That order matters. In Java, date and source are saved before persons is parsed, so a bad number leaves a half-updated search behind, and the next page shows it:

fn search_servlet(st: &mut Statics, params: &Params) -> Reply {
    let line = |n: u32| format!("servlets.SearchServlet.service(SearchServlet.java:{n})");
    st.search.date = params.get("date");
    st.search.source = params.get("source");
    st.search.destination = params.get("destination");
    match parse_int(params.get("persons").as_deref()) {
        Ok(persons) => st.search.persons = persons,
        Err(e) => return tomcat::exception(&e.at(&[&line(19)]).at(&SERVLET), false),
    }
    ...

Exceptions become values. parse_int returns a Result whose error is a Throwable: the class, the message and the stack frames Java would have printed. Each caller adds its own frames on the way up, the way the exception gathered them in Java. To get the frames right, parse_int follows Integer.parseInt line by line, because each way of failing throws from a different line:

while i < len {
    let d = digit(chars[i]);   // Character.digit: any Unicode decimal digit
    i += 1;
    if d < 0 {
        return Err(for_input(580));
    }
    if result < multmin {
        return Err(for_input(583));
    }
    result *= 10;
    if result < limit + d {
        return Err(for_input(587));
    }
    result -= d;
}

digit is Character.digit, which accepts the digits of every script, not just 0 to 9. We didn't guess which ones: we asked Java 1.8.0_282 to print them, and pasted the 35 ranges into the Rust. LocalDate.parse got the same treatment, error positions and messages included.

Let the JSP files write the pages

Jasper, Tomcat's JSP compiler, copies the text between <% %> tags to the response unchanged, Windows line endings included. Retyping that HTML into templates would be eleven chances to lose a byte. So the port reads the original .jsp files and walks their tags in order. Here is payment.jsp's Java, ported:

if invalid {
    p.println("Please enter valid passenger details");
    p.skip("}");
    return Ok(p);
}
p.expr("Booking.ticket_price", st.booking.ticket_price);
p.expr("Search.persons", st.search.persons);
p.expr(
    "Booking.ticket_price*Search.persons",
    st.booking.ticket_price.wrapping_mul(st.search.persons),
);
p.code("}");

Each call names the Java it stands for, and walking past a tag without handling it panics, so no piece of logic can be dropped quietly. wrapping_mul is there on purpose: Java's int overflows silently, and Rust's checks would panic instead.

Then give it real types

The default mode is where Rust's types come in. The static fields become one struct per visitor, kept in a session:

struct Trip {
    search: Option<SearchForm>,
    flight: Option<Chosen>,
    passenger: Option<Passenger>,
}

Each step checks that the steps before it happened. A visitor who opens the payment page without choosing a flight is sent back to the search, instead of seeing someone else's booking or the word null. The price is read from the table by flight id. Java took it from a hidden form field, so a visitor could pay Rs.1. The SQL values are bound. askama escapes every value unless told not to. And the admin password is an Argon2 hash that's never shown, instead of a static field printed on the login page.

Frameworks

With Spring, much of the behaviour sits in annotations rather than code. List them for each URL you move, and turn each into ordinary Rust:

  • Dependency injection becomes state you pass in. In axum, that's a struct given to the router, and each handler names what it needs.
  • JPA entities become structs and SQL. Watch for lazy loading, cascades and dirty checking, which run queries nobody wrote. sqlx's query! macros check each query against the real schema when the code compiles.
  • @Transactional becomes an explicit transaction: pool.begin(), then commit(). Note which exceptions rolled back and which didn't.
  • Bean Validation and Jackson become functions that return a Result, and serde. Check how Jackson wrote nulls, dates and enums, because clients read that format.
  • Spring Security becomes tower layers and extractors. Move the session format first, as above.

Matching the Edge Cases

Matching the edge cases: Tomcat's 500 page with the exception and frames from JDK 1.8.0_282; text written as ISO-8859-1, with form bodies read as Latin-1 and the JSP files' line endings kept; and exceptions that leave an update half done

Users don't see your code. They see the bytes Tomcat sent. Most of the differences we found were in those bytes, not the logic.

  • The error pages. Tomcat's 500 page lists the exception and the stack frames of the JDK, Jasper and the servlet, with line numbers, then the server version. Compat mode prints the same page, byte for byte, for every error we recorded. A JSP error even quotes the page's source around the failing line.
  • The charset depends on when it failed. A servlet that had called getWriter() before throwing fixes the response to ISO-8859-1, so the dash in the error page's title comes out as ?. One that hadn't gets UTF-8.
  • Text is Latin-1 both ways. Tomcat reads a form body with no charset as ISO-8859-1, and the pages are written in it. A UTF-8 name round-trips by luck. A € in a query string becomes ?.
  • int overflows. A ticket price of 2147483647 for five people is Rs.2147483643.
  • Methods. A JSP page answers GET, POST and HEAD, and lists GET, HEAD, POST, OPTIONS for anything else. A servlet with only doPost answers GET with 405 and PATCH with 501. SearchServlet overrides service(), so it answers every method, DELETE included.
  • Redirects are relative. Tomcat 9 sends Location: /search-results.jsp, a path rather than a full URL, over HTTP/1.1.

The repository had a worse problem than any of these. The JSP pages and a notes file contain the host, user and password of three hosted databases, in plain text. We removed them from our copy. If your legacy code has credentials in it, rotate them before the migration starts, because the migration means more people reading the code.

In the default mode the rest are fixed: a session per visitor, a hashed password, prices from the table, bound SQL, escaped output, a 400 page with the form for bad input instead of a stack trace, a card number that's checked and never stored, and admin pages that need a login. Those change what users see, so they belong in an announced release after the move. During the move, run compat mode.

Testing the Migration

Testing the migration: the same 13 recorded sessions go to Tomcat and to the Rust service, with Tomcat restarted before each one, and the status, headers and body are compared byte for byte. Tests for each fix cover the default mode, including two visitors at once

Many Java apps have plenty of unit tests and few that look at the HTTP response. The recordings fill that gap.

  • Replay the golden pairs against the Rust version. Our test starts a fresh app for each session, the same as restarting Tomcat, replays all 174 requests in compat mode, and compares the status, the headers and the body bytes. A failure prints the request and where the bodies first differ.
  • Check the check. We changed one byte in one recording and one status in another, and the test reported both. A test that can't fail proves nothing.
  • Replay from outside too. The capture script takes a base URL, so we pointed it at the running Rust service, and then at nginx with groups split between the two sides. Recording Java twice gave identical files, so the recordings are deterministic.
  • Unit tests for the fixed mode, one per fix, with a comment saying what Java did. Several use two visitors at once, because sharing between visitors was the biggest bug.
  • Mirroring in production. nginx's mirror directive can send a copy of real traffic to the Rust service, which throws its responses away, while you compare them offline. With state in memory, mirror whole sessions, not single requests, or the copies won't line up.

Finishing the Migration

Finishing the migration: each group has served real traffic from Rust without differences, the Java code and unused Maven dependencies are deleted, scheduled jobs and listeners are moved, Tomcat and the JVM are shut down, and the decisions are written down

A group is done when Rust has served it in production through a busy period, such as a holiday sale, with no differences in the replayed traffic and no complaints. Then:

  1. Delete the servlets, JSP pages and classes for that group, and any Maven dependencies nothing else uses. Unused Java left lying around is a trap for the next person who searches the codebase.
  2. Keep the nginx rules ready to switch back for a few weeks after each move.
  3. Move the scheduled jobs and the listeners. They're easy to forget, because nothing calls them.
  4. When the last group has moved, shut down Tomcat and remove the JVM from your images. Then switch to the default mode, as its own announced change.
  5. Write down the decisions you made along the way: which Java behaviour you copied, which you fixed, and why. Our example's README does this. That record replaces the knowledge that used to live in static fields and server settings.

One group at a time, and nobody outside the team ever notices the switch.

About MigrateX

MigrateX

MigrateX is our platform and service for moving software, data and infrastructure from one technology to another. It combines automation with experienced engineers. The automation does the repetitive work quickly, and the engineers make the tricky decisions.

This guide is how we approach Java to Rust projects with MigrateX. Here's what that looks like:

  1. Assessment. We list every URL, servlet, controller, filter, entity and scheduled job, and every place state lives in memory: static fields, singleton beans, sessions and caches. You see where the work is, and how it has to be grouped, before anyone agrees on a timeline.
  2. Plan. We work with your team to decide which groups move first, whether state moves out of memory before anything else, and which Java behaviour to copy exactly and which to fix on purpose.
  3. Migration, step by step. Automation handles the repetitive parts, like porting entities and queries to checked SQL and writing down the JDK's parsing rules. Our engineers handle the parts that need thought, like sessions, transactions and framework behaviour.
  4. Proof that it works. We record real traffic and replay it against both versions. A group only counts as moved when the responses match.
  5. Handover and clean-up. We remove the old code and the JVM, keep a way to switch back until things are quiet, and leave your team with a Rust codebase they understand and own.

What you get along the way:

  • No big launch day. Your app keeps running and getting new features while groups of URLs move one at a time.
  • Less risk. Replayed traffic and a one-line way to switch back mean users won't notice the move.
  • A team that's ready. We work alongside your developers the whole time, so they're comfortable with Rust well before the last .java file is gone.
  • More than one kind of move. We use the same approach for COBOL and PHP, for front ends like Angular, Ember and jQuery, and for data and infrastructure moves too.

To see the code behind this guide, visit github.com/cobuild-tech/migratex-examples. Got a Java service that needs too much memory, starts too slowly, or keeps throwing NullPointerException? We'd love to hear about it. Tell us a little about it through Contact Us, and we'll start with a free chat about where the work is likely to be.

References

Migration strategy

  1. M. Fowler. StranglerFigApplication. martinfowler.com, 29 June 2004. https://martinfowler.com/bliki/StranglerFigApplication.html
  2. M. Feathers. Working Effectively with Legacy Code. Prentice Hall, 2004.

Java and Tomcat

  1. Oracle. Integer.parseInt, Java SE 8 API. https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseInt-java.lang.String-
  2. Oracle. DateTimeFormatter.ISO_LOCAL_DATE, Java SE 8 API. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE
  3. Apache Tomcat. Tomcat 9 Configuration Reference: The HTTP Connector (URIEncoding). https://tomcat.apache.org/tomcat-9.0-doc/config/http.html
  4. Apache Tomcat. Tomcat 9 Configuration Reference: The Context Container (useRelativeRedirects). https://tomcat.apache.org/tomcat-9.0-doc/config/context.html
  5. Spring Framework. Bean Scopes. https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html
  6. Spring Session. https://spring.io/projects/spring-session

The example

  1. A. Gogoi. FlyAway: a flight-booking web app with JSP and Servlets. GPL-3.0. https://github.com/abhinov-gogoi/FlyAway
  2. CobuildX AI. migratex-examples: FlyAway and its Rust rewrite, with golden sessions recorded from Tomcat 9.0.44 and an nginx route switch. https://github.com/cobuild-tech/migratex-examples/tree/main/java-rust