What is a servlet?

ยท

2 min read

A servlet is a Java class that runs on a web server and handles requests from web clients (such as browsers). A servlet can generate dynamic web content, such as HTML, XML, JSON, etc. A servlet can also interact with databases, files, and other web resources.

Servlet API ๐Ÿ“š

The servlet API is a set of interfaces and classes that define how a servlet communicates with the web server and the web client. The servlet API is part of the Java EE (Enterprise Edition) specification. The servlet API consists of two packages: javax.servlet and javax.servlet.http.

The javax.servlet package contains the core interfaces and classes for servlets, such as Servlet, ServletConfig, ServletRequest, ServletResponse, etc.

The javax.servlet.http package contains the HTTP-specific interfaces and classes for servlets, such as HttpServlet, HttpServletRequest, HttpServletResponse, etc.

Life cycle of a servlet ๐Ÿ”„

The life cycle of a servlet describes the stages that a servlet goes through from its creation to its destruction. The life cycle of a servlet can be summarized in three steps:

  1. Initialization: The web server loads the servlet class and creates an instance of the servlet. The web server then calls the init() method of the servlet to initialize it. The init() method is called only once for each servlet instance.

  2. Service: The web server invokes the service() method of the servlet to handle requests from web clients. The service() method can delegate the request to other methods based on the HTTP method (such as doGet(), doPost(), etc.). The service() method is called multiple times for each servlet instance, once for each request.

  3. Destruction: The web server calls the destroy() method of the servlet to terminate it. The destroy() method is called only once for each servlet instance, when the web server decides to unload the servlet (such as when the web server shuts down or when the servlet is idle for a long time).

The following diagram illustrates the life cycle of a servlet:

sequenceDiagram
    participant Web Server
    participant Servlet
    Web Server->>Servlet: load and create
    Servlet->>Web Server: init()
    loop service()
        Web Server->>Servlet: request
        Servlet->>Web Server: response
    end
    Web Server->>Servlet: destroy()
ย