Dev Learning Lab

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

Fundamentals › Spring

Servlets

Which class is called a servlet?

Why it exists — To answer a web request in Java, you originally have to write everything yourself: accepting the network connection, reading the incoming text and splitting it into the address and headers, and building and sending the response text. A servlet is the standard Java web way of dividing this work so that a servlet container such as Tomcat handles these tasks, and the developer only writes a method (doGet) that says "when a GET request comes to this address, answer like this."

Where it's used today — These days you rarely write a servlet class yourself, and you use a Spring controller instead. Even so, when Spring Boot runs, it registers one servlet (DispatcherServlet) with Tomcat and has it receive all requests, so you often see the name servlet in error messages and logs.

A servlet is a Java class declared with class. It differs from an ordinary class in two places. extends HttpServlet is what qualifies the class to receive web requests, and @WebServlet("/hello") registers that a request the browser sends to the path /hello is handed to this class. You remove these two one at a time and send the same request, to see whether Tomcat calls the doGet of this class.

Checked against real execution · Deployed all 12 combinations on Tomcat 11.0.24, sent requests, and checked against the results

Concepts in this lab

Servlet class
A servlet class is a Java class that implements the Servlet interface. Instead of implementing the interface directly, you usually extend HttpServlet, which already implements it. The developer does not create an object of a servlet class with new. The servlet container creates it, and when a request arrives, the container calls a method of that object. The container creates only one object for each servlet declaration and keeps using it. Both the class and the object that the container created are called a servlet.
HttpServlet
Why it exists — The Servlet interface is not made only for HTTP, so if you implement it as it is, you must first sort out whether the request is GET or POST yourself. HttpServlet does that in advance, so you write only doGet or doPost to make a servlet that answers HTTP requests.
Where it's used today — DispatcherServlet, which Spring registers in Tomcat, is also a class that extends HttpServlet, so in the error log of a Spring server you often see the line HttpServlet.service. When you receive requests with only servlets without Spring, you extend this class and override doGet and doPost.
HttpServlet is an abstract class in the servlet API that you extend to make a servlet that receives HTTP requests. It already implements the Servlet interface that every servlet must implement, so the developer only writes extends HttpServlet and overrides methods such as doGet or doPost. When a request arrives, the service method of HttpServlet looks at the HTTP method of the request and calls the matching doXxx method. If a request comes in for a doXxx method that was not overridden, an error response saying that the HTTP method is not supported is sent.
@WebServlet
Why it exists — When there were no annotations, the name and address of each servlet had to be written separately in the web.xml file, so a class and the address it handles were split across different files. @WebServlet lets you write the address right above the class, so that you can tell from the code alone which address it handles.
Where it's used today — You use it when you build a small web program with only servlets without Spring, or when you learn servlets. In a Spring Boot project, instead of this, you decide the address by attaching an annotation such as @GetMapping to a controller method.
@WebServlet is an annotation that declares a class as a servlet and writes the paths (URL patterns) that the servlet handles. When the servlet container deploys the application, it reads this annotation and pairs the paths with the servlet. At least one path must be written, and a class with this annotation must extend HttpServlet. Adding the annotation does not turn an ordinary class into a servlet. The same registration can also be written in a configuration file called web.xml.
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.

Try these

Running with the default settings

  1. The server starts. Tomcat scans the class files of the web application and looks for classes with @WebServlet. It finds it on the Hello class, so Tomcat writes the path and the class written there into the path table. No object is created yet.
  2. You type localhost:8080/hello in the address bar of the browser, and the browser sends a GET /hello request to the server.
  3. Tomcat looks for the path /hello in the path table. The Hello class is written there.
  4. Tomcat creates an object of the Hello class. The code we wrote has no line new Hello(). Tomcat creates the servlet object.
  5. Tomcat passes the request to this object. The code in HttpServlet sees that it is a GET request and calls the doGet that we wrote. We did not write the line that calls doGet either. The text that doGet writes to the response is "Hello".
  6. The browser receives a 200 response. The body is "Hello".

Result of this run

Code

// Registration: hand requests for this path to this class
@WebServlet("/hello")
// Qualification: a servlet class that can receive web requests
public class Hello extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/plain; charset=UTF-8");
        resp.getWriter().write("Hello");
    }
}

Assumptions of this model

The servlet container is Tomcat 11.0.24 (Jakarta Servlet 6.1), and the model assumes that the browser sends one GET request per path, one after another. The localhost:8080 in the paths is an example of running Tomcat on its default port on my own computer. All 12 combinations were checked against the result of compiling the same source as the code on the screen, putting it in the web application folder (WEB-INF/classes), starting a real Tomcat, and sending the requests. What was checked is whether the class is of the Servlet type, the path table of Tomcat, the status code and body of the response, the number of objects created, and the number of doGet runs. That every servlet implements the Servlet interface and that HttpServlet is an implementation of it follow chapter 2 of the Jakarta Servlet specification, and that a class annotated with @WebServlet must extend HttpServlet and must have at least one path written on it follows section 8.1.1 of the specification. The screen shows the qualification with extends HttpServlet alone, but the exact condition is to implement the Servlet interface, and extending HttpServlet is the most common way. A path can also be registered with the web.xml configuration file or in code instead of @WebServlet, but only @WebServlet is covered here. The code on the screen leaves out the import lines and the @Override that is commonly put on an overridden method. That a plain class with only @WebServlet gets a 500 for the first request and a 404 from the next request to the same registration on is not defined by the specification but is a behavior observed on this Tomcat version. The calls to init and service that Tomcat goes through from creating the object to reaching doGet are left out, and they are covered in the in-depth lab "Servlets".

Previous lab: AOP and proxies · Next lab: Controllers

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these