Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

JSP and Servlets
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
  • The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy
  • Servlet Request Parameters, and Forward vs Redirect
  • Run a Java Web App in Docker: Tomcat 11 With One Compose Command
  • Sessions, Cookies and Filters in Java Servlets: Log In Once, Stay Logged In
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • JSP Scripting: Expressions, Scriptlets, Declarations, Comments and Includes
  • JavaBeans and JSP Scopes: Page, Request, Session and Application
  • JSP Expression Language Step by Step: ${...} for Beans, Maps, Lists, Params and Scopes
  • JSTL Core Tags: c:set, c:out, c:if, c:choose and c:forEach
  • JSTL Functions and Formatting: fn:length, fn:toUpperCase, fn:contains, fmt:formatNumber and fmt:formatDate
  • Maintaining and Migrating Legacy JSP With AI: Explain the Page, Refactor to a DAO, Servlet and JSTL, Then Move It to React
  • MVC and the Front Controller With Servlets and JSP
  • Forms With JSP and Servlets: Handle the POST and Validate on the Server
  • Mini App With Servlets and JSP: Login, Logout and a Shared Web Template
  • SQLite and a JDBC Connection Pool in a Java Web App
  • Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO
  • Users CRUD With Servlets and JSP, Part 2: Update and Delete
  1. Blog
  2. /
  3. JSP and Servlets
  4. /
  5. JSP

Maintaining and Migrating Legacy JSP With AI: Explain the Page, Refactor to a DAO, Servlet and JSTL, Then Move It to React

One tangled orders.jsp glues the status into SQL, opens a connection it never closes, mixes Java into HTML and styles inline. Three prompts explain it, refactor it to a DAO, a servlet and an EL plus JSTL page, and migrate the table to React 19 with TypeScript. The review catches two draft bugs: a javax taglib URI and an unescaped customer name.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026JSP

What you will learn

  • Spot the four usual problems in a legacy JSP: SQL built from input, database code in the page, scriptlets and inline styles
  • Prompt AI to explain a page before changing it
  • Refactor to a DAO with a PreparedStatement, a servlet and a JSP that uses only EL and JSTL
  • Migrate the table to a typed React component, review the AI draft line by line, and decide when to refactor in place or migrate

Before you start

  • JSP, servlets and EL basics
  • Some React and TypeScript helps

Almost every company has old JSP pages, and sooner or later someone has to touch them. This article takes one tangled page and lets AI explain it, clean it up and move it to React, in three steps: explain, refactor, migrate. AI does the typing. Your job is the judging, and the foundations in this article are what you need to do it.

One legacy page, four problems

<%@ page import="java.sql.*" %>
<html><body bgcolor="#EEEEEE">
<h2 style="color:navy">Open orders</h2><table border="1">
<%
  String st = request.getParameter("status");
  Connection c = DriverManager.getConnection(
      "jdbc:h2:~/shop", "sa", "");
  Statement s = c.createStatement();
  ResultSet r = s.executeQuery(
      "select * from orders where status='" + st + "'");
  while (r.next()) {
    boolean big = r.getDouble("total") > 500;
%>
<tr style="color:<%= big ? "red" : "black" %>">
  <td><%= r.getString("customer") %></td>
  <td><%= r.getDouble("total") %></td></tr>
<% } %>
</table></body></html>
  1. The status is glued into the SQL text, so a crafted value changes the query.
  2. The database code sits inside the page, and the connection is opened and never closed.
  3. Java and HTML are mixed with scriptlets, so the flow is hard to follow.
  4. Styling is inline, with bgcolor and style attributes.

(What scriptlets are and why they fell out of favour is in JSP scriptlets, expressions and declarations.)

Step 1: ask AI to explain

Explain this JSP page step by step, then list every problem, most serious first.

A good answer says what the page does: it reads status from the URL, opens a connection, runs one query and prints a row for each order. Then what is risky: the status goes straight into the SQL, the connection is never closed, and if the status is missing the query searches for the word null. Then what to do next: move the query into a Java class and keep only the display in the JSP. Understand the page first, then change it.

Step 2: refactor to a DAO, a servlet and JSTL

Refactor this page. SQL goes in a DAO, a servlet handles the request, the JSP uses EL and JSTL, and the styles go in a CSS file.

public record Order(long id, String customer, double total) { }

public class OrderDao {

    private static final String URL = "jdbc:h2:~/shop";

    public List<Order> findByStatus(String status) throws SQLException {
        String sql = "select id, customer, total from orders where status = ?";
        List<Order> result = new ArrayList<>();
        try (Connection c = DriverManager.getConnection(URL, "sa", "");
             PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setString(1, status);
            try (ResultSet r = ps.executeQuery()) {
                while (r.next()) {
                    result.add(new Order(r.getLong("id"), r.getString("customer"), r.getDouble("total")));
                }
            }
        }
        return result;
    }
}

The ? placeholder keeps the status out of the SQL text, and try-with-resources always closes the connection.

@WebServlet("/orders")
public class OrderServlet extends HttpServlet {

    private final OrderDao dao = new OrderDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String status = req.getParameter("status");
        if (status == null || status.isBlank()) {
            status = "OPEN";
        }
        try {
            req.setAttribute("orders", dao.findByStatus(status));
        } catch (SQLException e) {
            throw new ServletException(e);
        }
        req.getRequestDispatcher("/orders.jsp").forward(req, resp);
    }
}
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
  <link rel="stylesheet"
        href="${pageContext.request.contextPath}/css/orders.css">
</head>
<body>
<h2>Open orders</h2>
<table>
  <c:forEach var="o" items="${orders}">
    <tr class="${o.total > 500 ? 'big' : ''}">
      <td><c:out value="${o.customer}"/></td>
      <td>${o.total}</td>
    </tr>
  </c:forEach>
</table>
</body>
</html>

No scriptlets are left. The page only displays what the servlet gives it, and each part has one job. This is the MVC split described in MVC with servlets and JSP, and the ${...} syntax is in JSP Expression Language.

Three versions of the same orders table. Before: one JSP with SQL, connection, scriptlets and inline styles. Refactored: OrderDao with a PreparedStatement, OrderServlet that sets the orders, and an orders.jsp with c:forEach and c:out. Migrated: App fetches orders as JSON and passes them to an OrderTable React component; c:forEach becomes orders.map, the EL expression becomes curly braces, class becomes className. Before: orders.jsp SQL built from inputconnection never closed scriptlets in HTMLinline styles Refactored OrderDao: PreparedStatementOrderServlet: sets orders orders.jsp: c:forEach, c:outorders.css Migrated: React App: fetch orders JSONOrderTable: orders.map {o.customer}, classNamered rows above 500 kept
Explain, refactor, migrate. Each step keeps the red rows above 500.

Step 3: migrate to a React component

Migrate the order table to a React 19 component with TypeScript, and keep the red rows above 500.

export type Order = { id: number; customer: string; total: number }

export function OrderTable({ orders }: { orders: Order[] }) {
  return (
    <table>
      <tbody>
        {orders.map((o) => (
          <tr key={o.id} className={o.total > 500 ? 'big' : ''}>
            <td>{o.customer}</td>
            <td>{o.total.toFixed(2)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  )
}
export default function App() {
  const [orders, setOrders] = useState<Order[]>([])

  useEffect(() => {
    fetch('/orders.json')
      .then((res) => res.json())
      .then(setOrders)
  }, [])

  return (
    <>
      <h2>Open orders</h2>
      <OrderTable orders={orders} />
    </>
  )
}

The pieces map across: c:forEach becomes orders.map, the ${...} expression becomes curly braces, and class becomes className. React escapes text in curly braces by default, so the customer name is shown and not run.

Review: two issues in the first draft

AI wrote a fast first draft, and it was not perfect.

Issue in the draftWhy it breaksFix
The old taglib URI from the javax daysJSTL 3 on Tomcat 11 does not know ituri="jakarta.tags.core"
The customer name printed directly with ${o.customer}A name containing a script would run in the browser<c:out value="${o.customer}"/>, which escapes it

AI gives the draft, and you review it line by line.

Refactor in place, or migrate?

Refactor in place whenMigrate to React when
The page works and users are happyThe screen needs rich interaction
The changes are smallYou want one JSON API for many screens
Your team knows JSP and servletsYou can move one page at a time

A third option for a Java team is to keep server rendering and add interaction with Thymeleaf and htmx.

Keep going in JSP and Servlets · 13 of 19

Previous
JSTL Functions and Formatting: fn:length, fn:toUpperCase, fn:contains, fmt:formatNumber and fmt:formatDate
Next post
MVC and the Front Controller With Servlets and JSP
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet

A JSP looks like HTML with a little Java, yet Tomcat runs it as a servlet. See what a servlet container does for each request, what the generated hello_jsp.java looks like, what a .war holds, and Tomcat vs TomEE.

JSP Scripting: Expressions, Scriptlets, Declarations, Comments and Includes

The JSP tags you'll read in older Java web apps: expressions, scriptlets, declarations, page imports, two kinds of comment, and the include directive versus the jsp:include action, each shown with what Tomcat turns it into.

JavaBeans and JSP Scopes: Page, Request, Session and Application

A Student bean filled from a form with jsp:useBean and setProperty, then one Counter class kept in four scopes. Three visits, two browsers and an include page show exactly who sees which number.

JSP Expression Language Step by Step: ${...} for Beans, Maps, Lists, Params and Scopes

Expression Language prints a value in a JSP with ${...} and no Java on the page. Read a Student bean, a price map, a tag list and ?city=Boston, run small checks, and see the order EL searches the scopes.

On this page

  • One legacy page, four problems
  • Step 1: ask AI to explain
  • Step 2: refactor to a DAO, a servlet and JSTL
  • Step 3: migrate to a React component
  • Review: two issues in the first draft
  • Refactor in place, or migrate?
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.