Building a JSP Data Table with a Clear Servlet Boundary

Editorial illustration.

Originally published 26 June 2023; rewritten and reviewed on 15 October 2026.

Developers who come to Java web projects from ASP.NET WebForms often look for a drop-in <asp:GridView> equivalent in JSP. When they realise JSP does not ship with a stateful server-side grid control out of the box, the temptation is to open a Connection and ResultSet right inside <% ... %> scriptlets and loop out <tr> tags in the middle of the HTML.

That works for a three-row university demo, and then collapses in real enterprise or government Java apps the moment you need pagination, sorting, error handling, or protection against Cross-Site Scripting (XSS). Keeping the data retrieval in a Servlet and treating the JSP purely as a template makes the table far easier to maintain.

Let the Servlet and DAO handle SQL, paging, and sorting

Your Servlet’s doGet method should validate the incoming query parameters, fetch a bounded page of records from a DAO, attach the result to the request, and forward to the JSP. Never select an unbounded table just because it only has 50 rows in development.

@WebServlet("/customers")
public class CustomerListServlet extends HttpServlet {
    private static final int PAGE_SIZE = 20;
    private static final Map<String, String> ALLOWED_SORTS = Map.of(
        "name", "customer_name",
        "code", "customer_code",
        "created", "created_at"
    );

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int page = parsePositiveInt(req.getParameter("page"), 1);
        String sortParam = req.getParameter("sort");
        String orderBy = ALLOWED_SORTS.getOrDefault(sortParam, "customer_name");

        List<CustomerRow> rows = customerDao.findPage(page, PAGE_SIZE, orderBy);
        int totalRows = customerDao.countAll();
        int totalPages = Math.max(1, (int) Math.ceil((double) totalRows / PAGE_SIZE));

        req.setAttribute("rows", rows);
        req.setAttribute("currentPage", page);
        req.setAttribute("totalPages", totalPages);
        req.getRequestDispatcher("/WEB-INF/views/customers.jsp").forward(req, resp);
    }
}

Notice the ALLOWED_SORTS map. You cannot bind an ORDER BY column name as a JDBC PreparedStatement ? parameter, so whitelisting user input against a fixed map of safe column names is mandatory to prevent SQL injection. Inside customerDao.findPage, use PreparedStatement with LIMIT ? OFFSET ? (or OFFSET ? ROWS FETCH NEXT ? ROWS ONLY on SQL Server/Oracle) so the database only returns the 20 rows you actually intend to render.

Putting the JSP inside /WEB-INF/views/ is also deliberate: it prevents users from hitting /customers.jsp directly in the browser and bypassing your Servlet’s authorisation and data loading.

Render values safely with JSTL

In the JSP itself, avoid <% %> scriptlets and raw ${row.customerName} EL expressions for user-supplied strings. Use JSTL’s <c:out> tag so characters like <, >, and & are HTML-escaped automatically:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<c:choose>
  <c:when test="${empty rows}">
    <p>No customer records found.</p>
  </c:when>
  <c:otherwise>
    <table>
      <thead>
        <tr>
          <th scope="col"><a href="?sort=code">Code</a></th>
          <th scope="col"><a href="?sort=name">Customer</a></th>
          <th scope="col">Email</th>
        </tr>
      </thead>
      <tbody>
        <c:forEach var="row" items="${rows}">
          <tr>
            <td><c:out value="${row.customerCode}" /></td>
            <td><c:out value="${row.customerName}" /></td>
            <td><c:out value="${row.email}" /></td>
          </tr>
        </c:forEach>
      </tbody>
    </table>

    <nav aria-label="Pagination">
      <span>Page <c:out value="${currentPage}" /> of <c:out value="${totalPages}" /></span>
      <c:if test="${currentPage > 1}">
        <a href="?page=${currentPage - 1}">Previous</a>
      </c:if>
      <c:if test="${currentPage < totalPages}">
        <a href="?page=${currentPage + 1}">Next</a>
      </c:if>
    </nav>
  </c:otherwise>
</c:choose>

Check your stack’s JSTL URI carefully: Jakarta EE 10+ (Tomcat 10.1+, WildFly 27+) uses jakarta.tags.core, whereas older Java EE 8 / Tomcat 9 applications use http://java.sun.com/jsp/jstl/core. Mixing javax.servlet and jakarta.servlet libraries in the same pom.xml or WEB-INF/lib folder is one of the most common reasons a JSP fails to compile.

Test the edge cases that break demos

Before calling the table done, test three specific cases:

  1. A customer name containing <script>alert(1)</script> or O'Connor & Sons — it should appear verbatim as text, never execute or break HTML layout.
  2. An empty result set or ?page=999 beyond the last page — the view should show a clean empty state instead of a NullPointerException or blank white table.
  3. An invalid ?sort=drop_table parameter — it should fall back silently to the default sort column.

Once the Servlet-to-JSP contract handles those cleanly, adding search filters or CSV export on top of the same DAO is straightforward.