Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Build a Mini Servlet Container

Build a tiny servlet-style web container in Java with context paths, a filter chain, cookie sessions and a worker pool, to understand how Tomcat handles requests.

The best way to understand a server is to build a tiny one. In this project you will write a mini servlet container in plain Java: it listens on a port, maps URL paths to handler objects ("servlets"), runs requests through a filter chain, keeps cookie-based sessions and processes requests on a worker pool. It is a toy, not Tomcat, and says so: it uses the JDK's built-in com.sun.net.httpserver instead of Tomcat's connector, and it is nowhere near the Servlet specification. But every concept here has a direct counterpart in Tomcat, and building it makes the earlier lessons (sessions, filters, thread pools) concrete.

All code runs on this site's Java runner: the server and its client both live in one program, on the loopback interface, so you see the whole conversation.

The architecture

Our class Tomcat equivalent
HttpServer + executor Connector, acceptor/poller and worker pool
Servlet interface jakarta.servlet.Servlet
path to servlet map context path and servlet mappings in web.xml
Filter chain servlet filters
SessionStore the session Manager
Set-Cookie: JSESSIONID the session cookie
flowchart LR
  R["HTTP request"] --> W["Worker thread"]
  W --> F["Filter chain"]
  F --> S["Session lookup"]
  S --> V["Servlet"]
  V --> O["Response"]

Each request runs on one worker thread, through filters, with its session resolved before the servlet runs.

Step 1: the container and a hello servlet

First the minimum: register a handler for a path and call it from a client in the same program. The container picks a free port (port 0) so it never clashes with anything.

Java Step 1: a servlet and a request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The 404 and 500 cases map to what Tomcat does when no servlet matches and when one throws.

Step 2: filters and sessions

Now add the two features that make a container useful: a filter chain and cookie sessions. A session is a map stored under a random id sent in JSESSIONID; the container looks it up before calling the servlet and creates one when asked. The servlet receives a Session object, like request.getSession().

Java Step 2: filters and cookie sessions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The client's CookieManager plays the browser: it stores JSESSIONID from the first response and sends it back, so every request reaches the same session. The first /admin is denied; after /login stores the user in the session, the same request succeeds. Only one session exists because one cookie was reused. The log lines show the filter running around each servlet call, in the same order as Tomcat's filter chain.

Step 3: ideas to extend it

You now have the skeleton of a container. Each of these additions matches a Tomcat feature you have met:

  • Session timeout and sweeper: store last access time and remove idle sessions (session manager).
  • Thread pool limits: use a bounded queue and reject with 503 when full (connector tuning).
  • Access log: write a line per request with the elapsed time (access logs).
  • Context paths: load several "applications" under /shop and /blog with isolated sessions.
  • Request ids in a header and the log to follow a request through filters.
  • Security: a role check filter and an IP allow list (valves).
  • Graceful shutdown: stop accepting, let in-flight requests finish, then exit.

What the toy leaves out

Real Tomcat adds a great deal: the full Servlet API (request and response objects, async processing, multipart, listeners), a classloader per web application, JSP compilation, hot redeploys, TLS, HTTP/2, a proper security realm, clustering and thousands of edge cases in the HTTP protocol. The toy is useful because the core loop is the same: accept, find a handler, run filters, resolve a session, write a response.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which part of Tomcat does the worker thread pool in our toy correspond to?

    Tomcat's connector hands requests to a pool of worker threads, like the fixed pool here.
  2. 2. How does the container recognize a returning visitor?

    The cookie carries the id of the session stored on the server, as in Tomcat.
  3. 3. Why does the first /admin request return the denied message?

    The filter checks the session for a user and short-circuits the chain when it is missing.
  4. 4. What does the toy use instead of Tomcat's Coyote connector?

    It is a teaching tool that reuses the JDK's small HTTP server for the network part.

Summary

  • A container accepts requests on a worker pool, maps paths to servlets and runs filters around them.
  • Sessions are server-side maps found through a JSESSIONID cookie.
  • A filter can short-circuit the chain, which is how security and CSRF checks work.
  • The toy shows the shape of Tomcat; the real server adds the full spec, classloaders, TLS, clustering and much more.

Next: Practice exercises and interview questions