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:
- 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. Theinit()
method is called only once for each servlet instance. - Service: The web server invokes the
service()
method of the servlet to handle requests from web clients. Theservice()
method can delegate the request to other methods based on the HTTP method (such asdoGet()
,doPost()
, etc.). Theservice()
method is called multiple times for each servlet instance, once for each request. - Destruction: The web server calls the
destroy()
method of the servlet to terminate it. Thedestroy()
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()
Top comments (1)
Can a servlet run outside web server? It is often desirable to separate presentation from business logic.