Why React Inside JSP?
Our dashboard was built on server-rendered JSP pages with jQuery. Every new feature meant more JSP, and building features that way felt slow. What we really wanted was to move the whole frontend to React.
But in early 2024, a full migration wasn’t realistic. Rewriting every page would take a long time, and we couldn’t stop shipping features while we did it.
So we made a simpler rule: the old pages stay as they are, and every new feature gets built in React (with Vite, Tailwind CSS, and shadcn/ui). Over time, more and more of the app becomes React, one feature at a time.
Every page is JSP. Press play.
The Small Problem
There was one catch.
How in the hell do you stuff React inside a page the server already rendered?
React expects to own the page. It wants an index.html, a <div id="root">, and a bundle that boots everything up. A JSP page is HTML put together on the server by Java, with jQuery sprinkled on top. They don’t naturally fit together.
So we started experimenting. Every fix we found uncovered the next problem, and it took a lot of trial and error. Here’s how it played out.
Starting Simple: A Whole Page in React
The first thing we tried was the easy case: a page where React owns everything except the shared sidebar. Vite builds the React app into a /react-app folder that the Java app serves, and the build gives us an index.html that loads the app’s JS and CSS:
<!-- /react-app/index.html (generated by Vite, trimmed) -->
<script type="module" src="/react-app/assets/index.js"></script>
<link rel="stylesheet" href="/react-app/assets/index.css" />
<div id="root"></div>
That index.html is the entry point, and including it beats copying its script tags into the JSP: Vite gives the JS and CSS files new names whenever they change, so the JSP never has to know them. It’s the full file Vite generates, <html> and <head> included, and that’s fine. Browsers ignore the extra wrapper tags once it lands inside the page, so the scripts and styles still load.
To put a React page next to the legacy sidebar, the JSP renders the sidebar as usual and includes the React build in the content area. Our dashboard home page works this way:
<!-- layout.jsp (trimmed) -->
<%-- legacy sidebar: sidebar.jsp --%>
<div class="content">
<jsp:include page="/react-app/index.html" />
</div>
The Java app serves /overview with layout.jsp. React boots inside the content area, sees the URL, and React Router renders the dashboard. The sidebar is still plain JSP.
Pages with no legacy chrome at all, like signup and login, are even simpler. The Java app skips the JSP entirely and returns React’s index.html as the whole page.
Here’s what happens on each kind of request:
One page: JSP around the edges, React inside.
index.html is on the page, React Router takes over.Either way, it worked. First problem solved.
Then the next feature came along, and it wasn’t a whole page.
Then We Needed Just One Section in React
This time, the feature had to sit inside an existing JSP page, right between two JSP components. Rebuilding the whole page in React for one feature made no sense. So how do you drop a React component in between?
To solve this, I built a small helper called mountReact. It works in three parts.
1. Load the React build on the JSP page. Same index.html as before, included once in the page. Here it’s only there to load React’s scripts. React renders into the feature divs by their ids:
<!-- page.jsp -->
<jsp:include page="/react-app/index.html"></jsp:include>
2. Mark the spot. Wherever the feature should appear, the JSP gets an empty div with an id:
<!-- page.jsp -->
<%-- JSP component above --%>
<div id="feature-name"></div>
<%-- JSP component below --%>
3. Render into it. mountReact finds that div and renders the right component inside it:
// mountReact.tsx (imports trimmed)
type MountConfig = {
selector: string;
Component: React.ComponentType;
};
export function mountReact({ selector, Component }: MountConfig) {
const container = document.querySelector(selector);
if (!container) {
return;
}
ReactDOM.createRoot(container).render(<Component />);
}
In main.tsx, every feature is one call. Each component is loaded with lazy and wrapped in Suspense, so React only downloads a feature’s code when its div is actually on the page:
// main.tsx (imports trimmed)
const NewFeature = lazy(() => import("@/new-feature"));
document.addEventListener("DOMContentLoaded", () => {
mountReact({
selector: "#feature-name",
Component: () => (
<Suspense fallback={<>Loading...</>}>
<NewFeature />
</Suspense>
),
});
});
Try it. Pick which divs this JSP page has, then fire the event:
main.tsx
mountReact("#usage-chart")waitingmountReact("#invite-modal")waitingmountReact("#activity-feed")waitingmountReact("#comments-panel")waiting
Network
- nothing downloaded yet
mountReact call. No div on the page means no render and no download.That’s the whole trick. From then on, every new feature on an old page followed the same recipe: an empty div in the JSP and one mountReact call. If the div isn’t on the page, nothing happens.
Second problem solved.
The Next Pain: No Hot Reload
Injecting React was sorted. But then a new problem showed up: building features this way was painful.
The JSP includes the built React files. So every time I changed a line of React, I had to rebuild, copy the output into the Java app, and reload the JSP page before I could see anything:
# build-and-copy.sh
npm run build
rm -rf ../java-app/react-app
cp -r dist ../java-app/react-app
In simple terms: no hot reloading. Every small CSS tweak meant a full build.
To fix this, we set up a dev-only JSP, vite-dev.jsp, which loads React straight from the Vite dev server on localhost:5173. Nobody edits pages by hand to use it: the JSP checks whether it’s running locally and picks the right include.
<%-- page.jsp --%>
<c:choose>
<c:when test="${isLocal}">
<jsp:include page="/vite-dev.jsp" />
</c:when>
<c:otherwise>
<jsp:include page="/react-app/index.html" />
</c:otherwise>
</c:choose>
And vite-dev.jsp itself:
<%-- vite-dev.jsp (local development only) --%>
<div id="root"></div>
<script type="module">
import RefreshRuntime from "http://localhost:5173/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/src/main.tsx"></script>
The first script sets up React Fast Refresh, the preamble Vite’s React plugin would normally inject into index.html for us. It looks scary, but it’s straight from Vite’s Backend Integration guide, which describes exactly this kind of setup, so you can copy it as is. Then @vite/client opens the hot-reload connection, and main.tsx loads straight from the dev server. On the Vite side, the dev server needs one extra setting:
// vite.config.ts (local dev)
export default defineConfig(({ command }) => {
if (command === "serve") {
return {
plugins: [react()],
server: { origin: "http://localhost:5173" },
};
}
return { plugins: [react()], base: "/react-app" };
});
server.origin makes the asset URLs inside modules point back at localhost:5173, so they still load even though the page itself comes from the Java app.
So the real JSP page gets hot reload, with the real session and the real legacy CSS, and changes show up instantly.
Type something in either task box if you like, then change the button colour in the code.
- Waited
- 0s
- Drafts lost
- 0
- Waited
- 0s
- Drafts lost
- 0
Then the CSS Broke
With hot reload working, we could finally see every change instantly. And that’s when the next problem became obvious: the CSS.
Tailwind and the legacy stylesheets were fighting over the same elements. Legacy inputs shrank, links turned grey, and shadcn selects went uppercase. That one needed its own post, which walks through how a tw- prefix and a scoped Preflight fixed it:
One Last Thing: Getting JSP and React to Talk
With the CSS under control, we hit one last, slightly unusual problem. Sometimes a click on the JSP side had to call a function inside React. Sometimes React had to push data back into the JSP page.
They’re on the same page but in two different worlds. React can’t import jQuery code, and jQuery can’t call into a React component’s state.
What they do share is window. So we used custom events.
Here’s the idea. Say there’s a JSP button, and clicking it should open a React modal. The button can’t call React directly, but it can send a custom event on window with dispatchEvent. React listens for that event name with addEventListener and opens the modal when it hears it. Neither side needs to know anything about the other.
The New project button is plain JSP. Click it and watch it open a React modal.
- Website redesign
- Mobile app launch
- Q3 planning
bridge:openNewProjectDialoglistening$("#new-project-button").on("click", () => {
window.dispatchEvent(
new CustomEvent("bridge:openNewProjectDialog")
);
});window.addEventListener(
"bridge:openNewProjectDialog",
() => setIsModalOpen(true)
);Now switch what React listens for and click again. The event still goes out, but nothing opens. That’s the only rule: both sides have to use the exact same event name.
JSP → React: Opening a Modal
The “New project” button is plain JSP markup, and its jQuery click handler fires an event on window:
// projects.js
$("#new-project-button").on("click", function () {
// React listens for this event and opens its modal.
window.dispatchEvent(new CustomEvent("bridge:openNewProjectDialog"));
});
The React modal listens for it and opens itself:
// new-project-modal/index.tsx
useEffect(() => {
function handleOpen() {
setIsModalOpen(true);
}
window.addEventListener("bridge:openNewProjectDialog", handleOpen);
return () =>
window.removeEventListener("bridge:openNewProjectDialog", handleOpen);
}, []);
A JSP button opens a React modal, and neither side knows anything about the other.
React → JSP: Sending Data Back
It works the other way too. Say the notifications panel is new, so it’s React, but the header with the little red unread badge is still JSP. When you read a notification in React, the badge has to go down. So React sends the new count over in the event’s detail:
// notifications-panel/index.tsx
// After a notification is marked as read:
window.dispatchEvent(
new CustomEvent("bridge:unreadCountChanged", {
detail: { count: unreadCount },
}),
);
And the legacy JS updates its badge:
// header.js
window.addEventListener("bridge:unreadCountChanged", function (event) {
$("#unread-badge").text(event.detail.count);
});
Wrapping Up
That’s the whole journey. We never did a big-bang migration. Each problem led to the next fix:
- ProblemReact wants to own the whole pageFixWhole pages: React’s index.html, included by a JSP or served as is.
- ProblemOne feature has to sit between two JSP componentsFixAn empty div in the JSP, and mountReact renders into it.
- ProblemEvery change needs a full buildFixvite-dev.jsp gives hot reload on real JSP pages.
- ProblemTailwind and the legacy CSS fightFixScoped CSS keeps them out of each other’s way.
- ProblemJSP and React can’t call each otherFixCustom events on window let them talk without knowing about each other.
Every new feature since early 2024 has shipped in React this way, while the old pages kept working the whole time.