Monday, April 6, 2009

The Servlet lifecycle in detail



When asked about the lifecycle of a servlet 75% of those on whom it is asked to will reply immediately “init, service, destroy”. So, isn’t that right? Yes, it is right, but it does not tell you everything about the servlet lifecycle. And before I had read the HFSJSP even I would have answered the same.

Now, let me tell you elaborately on what leads to a class being called a “servlet” or as it is said in HFSJSP “attaining servletness”. When you look at a class that extends the HttpServlet class you would find that there is nothing special about it. You don’t even find a main() in it. So how does it receive requests from the client and send back response?
As I have shown in the diagram the class that you’ve decided to use as a servlet (by extending HttpServlet/GenericServlet) is just a normal class until either the client sends a request to it or the container decides to load it by itself. All the container has to do to convert the class into a servlet is to create a ServletConfig object for the servlet and pass the reference to it. The creation of the ServletConfig object happens after the default constructor call. Therefore if you ever try to access the ServletConfig of the servlet in the default constructor, all you will ever get is a null.

This is why we are provided with the init() method. Once the ServletConfig is created the container calls the init() method. Now that the ServletConfig is created for the servlet we can get the reference using the getServletConfig() . The ServletConfig could then be used to obtain init parameters (using the getInitParameters() method) that you want to be constant for the servlet through out its life.(I assume that you know how to configure your init parameters in the Deployment Descriptor).

After this, for each request that the servlet receives, the service() method is called which in turn calls the doGet()/doPost… depending on the method of the request sent.

Finally when the container is about to be shut down (redeployed or server is restarted), the destroy() method of the servlet is called. And the servlet is no more.

I hope this helps you :). But make sure you take a look at the books to get a clearer picture of the servlet lifecycle.

No comments:

Post a Comment