The Java Servlet interface defines Servlet lifecycle methods to initialize the servlet, service requests, and remove the servlet from the server container. These are invoked in the following sequence:
The first client request should wait until the servlet object is created and initialized by the web container to handle the request. To avoid this we can also inform the servlet container to create the servlet object when the server starts.
When the servlet object is created the container initializes the servlet object by invoking the constructor. After the constructor, the lifecycle init() method is invoked.
The init method is invoked by the web container to indicate that the servlet can handle service requests. The signature of the init method is as follows:
public void init(ServletConfig config) throws ServletException
This method is called after instantiating the servlet. The servlet is created and then initialized with the init() method. The web container creates the servlet object whenever the first request is given to the servlet.
The service method is invoked by the servlet container that allows the servlet to accept the request and respond with a response. The method signature of the service method is as follows:
public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException
Once the servlet is initialized, it will be able to process the client’s request. The response is provided back to the client after processing the request. The service() method would be executed for each client request.
Servlets that run under the multithreaded web containers can handle multiple service requests simultaneously. Any calls from the clients to the service() method are handled.
The servlet is then destroyed with the destroy() method and sent for garbage collection. The method signature of the destroy method is as follows:
public void destroy()
The init() and destroy() methods are executed only once during the lifecycle of the Servlet. The destroy() method is invoked by the container whenever the server is shut down or when the servlet is removed( servlet undeploy) from the servlet.
Java Tutorial on this website:
For more information on Java, visit the official website :