Tuesday, August 10, 2010

Servlet Life Cycle

Servlets are those components managed by the web container. A servlet is managed thru a defined life cycle. In that life cycle we can see how it is loaded, instantiated and intialized, handles requests from the client machine and how it is taken out of the service.

Life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API and it should be implemented by all the servlets. A servlet should extend GenericServlet or HttpServlet abstract class directly or indirectly.

The life cycle methods of a Servlet defined in the Servlet Interface is as follows

1. Init

public void init(ServletConfig config) throws ServletException;

init() method will be called once when the servlet is loaded.

2. Service

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;

service() method is called when each request comes to the server from the client side

3. Destroy

public void destroy();

destroy() method is called by the JVM automatically which is more concerned with the garbage collection.

E.g. Create a Servlet class as follows.


When you load the servlet for the first time, init() method will be called and following to that the service() method is executed. The output will be as follows,


When you run the servlet for the second time, only the service() method is executed. Since the servlet instance is created and initialized once the count value will not be reset to zero. The output will be as follows,

No comments:

Post a Comment