Saturday, April 25, 2009

What are servlets, its fow control and life cycle

In general, Servlet is an Interface consisting of methods which every servlet needs to implement.
GenericServlet is an abstract class which implements some of the method of the Servlet Interface. Since the communication between the client and the server happens with the HTTP protocol, the generic servlet was further sub classed to HttpServlet. An httpServlet is an abstract class consists of all the methods which an servlet is required for Http Communication. 

Any HttpServlet which is written by the programmer should obey the following rules.
  1. The servlet written should be public ( since the container calls the servlet and its not called by any one else, since it does not have a Main class)
  2. The servlet written should extend the httpservlet class.
LifeCycle of a Servlet

There are in all 3 states in which a servlet can be
  1. init()
  2. service()
  3. destroy()
however there is a little more to this theory.
  1. When a container gets a request for the servlet, the container first loads the servlet class.
  2. Once the servlet class is loaded, the container executes the default constructor and instantiate the servlet class.
  3. The container calls the init() method to initialize the servlet. The initialization of the servlet happens only once in the life cycle of the servlet. This can be done at deploy time or at run time. 
  4. Once the servlet has been initialize the service method is called. At this stage the request is getting processed.
  5. Once all the request has been processed, the container calls the destroy method and the thread, the request, response objects and the servlet is being sdestroyed.
With the understanding of the life cycle of the servlet lets go and have a look at the servlet API. 

No comments:

Post a Comment