In Java, a Servlet is a server-side component that handles requests and generates responses. The lifecycle of a servlet is managed by the Servlet container (like Tomcat or Jetty), which is responsible for creating, initializing, handling requests, and destroying servlets. The lifecycle is defined by a series of stages:
Loading and Instantiation
- The servlet container loads the servlet class when the first request is made, or when explicitly configured to load at startup.
- The container creates an instance of the servlet by calling its default constructor.
Initialization (init() method)
- Once the servlet instance is created, the container calls the
init()
method. - This method is used for servlet initialization, such as setting up resources or reading configuration data.
- The
init()
method is called only once during the servlet’s lifecycle, immediately after the servlet is created.
1 2 3 |
public void init() throws ServletException { // Initialization code } |
Request Handling (service() method)
- After initialization, the servlet is ready to handle client requests.
- The
service()
method is called for every request, which takes a request and response object as parameters. - This method processes the request and sends back an appropriate response.
- The servlet can handle multiple requests concurrently, as each request is processed in its own thread.
1 2 3 |
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Request handling code } |
Destruction (destroy() method)
- When the servlet is no longer needed, or the server shuts down, the container calls the
destroy()
method. - This method is used for cleanup tasks like releasing resources (database connections, file handles, etc.).
- The
destroy()
method is called only once before the servlet is unloaded from memory.
1 2 3 |
public void destroy() { // Cleanup code } |