Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Spring › Web MVC

Servlets

How an HTTP request reaches Java code

Why it exists — To handle a web request in Java without servlets, you had to accept the connection with a socket and parse the HTTP text yourself, and the CGI approach, which starts the program as a new process for every request, became expensive as requests increased. A servlet leaves connection management and HTTP parsing to the container and calls a method of a servlet object, created once, on a thread for each request, so developers only need to write what to do for each address.

Where it's used today — It is rare to write a servlet directly, but a Spring MVC application runs through the servlet API on top of Spring Boot's embedded Tomcat. The filters that apply logging or authentication checks to every request, and the HttpServletRequest and HttpServletResponse that you receive as controller parameters, are the servlet API itself. When you must handle a very large number of connections with few threads, Spring WebFlux is sometimes used instead of Spring MVC.

What a browser sends is an HTTP request made of text. A servlet container such as Tomcat reads that text, turns it into Java objects, and calls the method of the servlet that is mapped to the path. A servlet is a Java class that "receives a request object and writes to a response object".

Checked against real execution · 48 different requests were sent to Tomcat 11.0.24 and Spring Boot 4.1.1 and checked against the results

Concepts in this lab

Servlet and servlet container
A servlet is the Java standard interface that receives an HTTP request, processes it, and produces a response. A servlet container (such as Tomcat) accepts network connections, parses requests, calls the right servlet, and manages the servlet lifecycle and the request-handling threads. Spring MVC runs on top of a single servlet called DispatcherServlet.
DispatcherServlet and the front controller pattern
Where it's used today — Spring Boot registers it automatically so that it receives requests for every path, so you almost never create it yourself. When you follow in a debugger which controller a request goes to, the doDispatch method is the starting point.
This is the servlet in Spring MVC that receives every HTTP request first. It coordinates the whole flow: it finds and calls the controller that handles the request, and it turns the result into a response. A structure like this, in which a single entry point receives all requests, does the common processing, and then hands each request to the part responsible for it, is called the front controller pattern.
Embedded server
Where it's used today — It suits deployment where a single jar file is made into a Docker image and run, and you change the port with the server.port setting. You can also switch to Jetty instead of the default, Tomcat.
This is a web server (Tomcat by default) that is included inside a Spring Boot application and runs together with it. You can run the application with a single java -jar command, without the steps of installing a server separately and deploying the application to it.
Web server and application server
Why it exists — If one application server takes on static file delivery and TLS handling in addition to running code, then every time you scale the application server to several machines or replace it, these settings also have to be adjusted on each server. If you put a web server in front, the shared work can be handled there, and the application server can concentrate on running code.
Where it's used today — A Spring Boot web application runs on embedded Tomcat by default, so it is itself an application server. In the cloud, a setup in which a load balancer or CDN takes TLS handling and static file delivery instead of a web server is also common.
A web server is a program that receives HTTP requests and either responds with static files such as images and HTML or forwards the requests to another server (Nginx, Apache). An application server (web application server) is a program that runs program code and builds a result for each request (Tomcat). A common setup puts a web server in front and passes requests on to the application server.
Tomcat's threading model
Why it exists — If one thread handles a request all the way through, even code that waits for a database response can be written from top to bottom in order, without being split into callbacks. Tomcat takes those threads from a pool created in advance and sets an upper limit on their number, so threads do not grow endlessly even when requests pile up.
Where it's used today — A Spring MVC service with slow external calls or many concurrent requests tunes server.tomcat.threads.max together with the size of the database connection pool. When requests seem to be stuck, you look in a thread dump to see at which line a request processing thread such as http-nio-8080-exec-1 is waiting.
Tomcat manages its request processing threads in a pool, and one thread takes one request and handles it until the response is finished. The number of requests it can handle at the same time is limited by the maximum number of threads (200 by default). Unlike the standard Java ThreadPoolExecutor, when no thread is idle it adds threads up to the maximum first, and new requests wait only when all of them are in use. A thread stays occupied even while the request is waiting on a database or an external call.
HTTP methods
The part of an HTTP request that indicates the action the request wants to perform on a resource. GET means read, POST means create or a processing request, PUT means replace the whole resource, PATCH means modify part of it, and DELETE means delete. Use each one according to its meaning so that HTTP behavior such as caching and retries works as expected.

Try these

Running with the default settings

  1. The server starts. Tomcat listens for connections on port 8080 and builds a table of "which servlet handles which path". It registers HelloServlet, which is annotated with @WebServlet("/hello"), as the servlet for /hello. The servlet object has not been created yet.
  2. Request #1: The browser connects to the server and sends an HTTP request. What it sends is a few lines of text, like the ones shown on the screen.
  3. Tomcat assigns a thread from its thread pool and parses the text it received into an HttpServletRequest object. It also creates an empty HttpServletResponse object to hold the response. The servlet does not have to parse the text itself. It only has to read the values from this object. Tomcat names its threads like http-nio-8080-exec-1.
  4. Tomcat looks in the table for the servlet mapped to the path /hello. It is HelloServlet.
  5. Tomcat creates the HelloServlet object at the first request. The developer does not create it with new. The container does. This one object is used until the server shuts down.
  6. HelloServlet.init() is called once. This is where the servlet does the setup it needs before it receives requests.
  7. Tomcat calls service(request, response) of HelloServlet. service() looks at the HTTP method of the request and calls doGet().
  8. doGet() runs the code that we wrote. It reads name from request and writes the status and the body to response.
  9. The method of the servlet has finished. Tomcat turns the content of the HttpServletResponse into the text of an HTTP response and sends it to the browser. It discards the request and response objects used for this request and returns the thread to the pool. The HelloServlet object stays as it is and waits for the next request.
  10. Request #2: The browser connects to the server and sends an HTTP request. What it sends is a few lines of text, like the ones shown on the screen.
  11. Tomcat assigns a thread from its thread pool and parses the text it received into an HttpServletRequest object. It also creates an empty HttpServletResponse object to hold the response. The servlet does not have to parse the text itself. It only has to read the values from this object. Which thread is assigned is not fixed, so the thread that handled the previous request may be assigned again.
  12. Tomcat looks in the table for the servlet mapped to the path /hello. It is HelloServlet.
  13. The HelloServlet object already exists. Tomcat does not create a new one and uses that object again. It does not call init() again either.
  14. Tomcat calls service(request, response) of HelloServlet. service() looks at the HTTP method of the request and calls doGet().
  15. doGet() runs the code that we wrote. It reads name from request and writes the status and the body to response.
  16. The method of the servlet has finished. Tomcat turns the content of the HttpServletResponse into the text of an HTTP response and sends it to the browser. It discards the request and response objects used for this request and returns the thread to the pool. The HelloServlet object stays as it is and waits for the next request.
  17. The server shuts down. Tomcat calls destroy() of HelloServlet once and then discards the object. This is the chance to clean up the resources that were opened.

Result of this run

Code

@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {

    @Override
    public void init() {                       // once, right after the object is created
        // setup work
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String name = req.getParameter("name");   // read from the request
        resp.setContentType("text/plain; charset=UTF-8");
        resp.getWriter().write("Hello, " + name);   // write to the response
    }

    @Override
    public void destroy() { }                  // once, when the server shuts down
}

Assumptions of this model

The model assumes that the servlet container is Tomcat and that requests arrive one at a time, in order. Three points follow the Jakarta Servlet specification and the documentation of HttpServlet: only one servlet object is created per servlet declaration, init and destroy are each called once, and a doPost that is not overridden returns 405. Only the main lines of the HTTP request and response text are shown. For the 36 combinations with a directly written servlet, requests were sent to a real Tomcat 11.0.24, and for the 12 combinations on the Spring MVC side, to a real Spring Boot 4.1.1, and it was confirmed that the response code, the counts of object creation, init, and request handling calls, and the time when the object was created match the screen. In this process, two points on the Spring side were corrected to match reality. The DispatcherServlet object is created when the server starts, not at the first request (only init happens at the first request), and the 404 and 405 responses are dispatched once more to /error, so there are two request handling calls per request. Among the entries for where the response was produced, "Default servlet of Tomcat" and "Default doPost of HttpServlet" were inferred from the response code and were not observed directly.

Previous lab: Connection pool and OSIV · Next lab: Spring MVC request flow

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these