Servlet life cycle

If you are all set to attend an interview related to J2EE/Java Web application development then, it is recommended to brush up this important concept.I witnessed this question in telephonic round interview. Today I am documenting it for future reference and for others.
What is Servlet ?:  A Servlet is a Java program that runs within a servlet container. Servlets receive and respond to requests from Web clients. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet". As every object is having a life-cycle so as of servlet instance.
The life-cycle of a servlet is controlled by the container in which the servlet has been deployed. Life cycle of servlet can be broadly divided into three stages :
1. Initialization stage -  init() -   Executed only once
2. Service stage -            service() -     For each request
3. Destroy stage. -          destroy() -     Executed only once
 We can represent all three method executing in servlet container as follows :
 
                                             Diagram taken from : http://www3.ntu.edu.sg/

1. Initialization phase : In this stage web-container initializes the servlet instance by calling the init() method and ONE instance per JVM for each servlet is created. It is important to note that init() method can be invoked in either of two ways :
1. On demand basis  - On arrival of first HTTP request for the given servlet .
2. On Servlet container start: When servlet container start,it reads the web.xml ,finds the declared servlets in the classpath and if <load-on-startup> is configured with an  integer value 0 or more then for the given servlet one instance of that servlet will be created and are stored in memory and reused every time the request arrives. (Always remember REUSED !!).Sample code for servlet config of  load-on-startup:
     <servlet>
           <servlet-name>controlServlet</servlet-name>
          //Mapping details .....
          <load-on-startup> 1 </load-on-startup>
    </servlet>
Note : load-on-startup can specify an (optional) integer value. If the value is greater than 0, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
Please note, init(ServletConfig) is being called by the servlet container to indicate a servlet that the servlet is being placed into service.We can override this init() method see this for reference. 
  public void init(ServletConfig config) throws ServletException 
  { 
       //some initialization - like getting database connection,
       // resource management etc.
   } 
Here is a visual explanation of Instantiation phase, in layman terminology.
Notes : 
  • init() is not the entry point of a servlet. servlet constructor is executed before execution of init() but it is not  recommended to use constructor for any Servlet. why? Find here
  • The container would decide how many instances of servlet would be instantiated upfront to cater the requests.This is container implementation..(Confused !! But it's fact)
2. Service phase : In this stage for every new request a new thread is created or allocated from a pool to invoke that servlet instance which was created in earlier stage . The HttpRequest and HttpResponse objects will be new for each new request.
One commonly asked question in interview : How HTTP request coming from web client is served by servlet ? 
On request arrival web container(servlet container) calls service() method of servlet and the service() method determines the kind of request and calls the appropriate method (doGet() or doPost() for handling the request and sends response to the client using response object. Lets consider following code blocks:
 public class SimpleHttpServlet extends HttpServlet {
  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {
      response.getWriter().write("<html><body>GET response</body></html>");
  }
  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response)
      throws ServletException, IOException {
      response.getWriter().write("GET/POST response");
  }
}
HttpServlet(javax.servlet.http.HttpServle) class reads the HTTP request(coming from client), and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.
Notes :
  • It is important to note that each request is served by a new thread if and only if our servlet is not implementing SingleThreadModel interface. It is not recommended to use SingleThreadModel interface. 
  • Is servlet threadsafe ? Answer is : No, but we can make by it thread-safe by following some standard so that it can serve multiple request in thread safe manner. How we can make servlet thread safe?
3. Destroy phase : When a servlet is unloaded by the servlet container, its destroy() method is called. It is executed only once in servlet life cycle. A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at run-time.

Refer J2EE developer interview questions

======================End of article=====================

10 Comments

  1. It is a great post. Keep sharing such kind of useful information.

    Education
    Technology

    ReplyDelete
  2. This post is really useful and helpful to know more about the things which you have shared. I appreciate you for such a great amount of information. I assure this would be beneficial for many people. Best Advanced Java & Data Structures Course In Delhi

    ReplyDelete
  3. Informative blog! I am truly awed by this blog post! Very clear explanation about the full stack Development. I agree with all points.Hire Full Stack Developers

    ReplyDelete
  4. Infotech Softnet is the best C++ institute in Janakpuri and caters to the needs of all the students. With a team of highly experienced trainers and a proven track record of success, we have earned a reputation as the best C++ institute in the area. Our comprehensive C++ courses are designed to cater to the needs of both beginners and advanced learners. We provide practical, hands-on training that enables our students to master the language quickly and effectively. Our state-of-the-art facilities and advanced teaching methodologies make us stand out from other computer training institutes in Janakpuri.
    Join Infotech Softnet Computer Education today and unlock your potential in C++. Whether you are looking to kickstart your career in programming or simply enhance your skills, we have a course for you.

    ReplyDelete
  5. It is quite helpful that you have offered this information on your blog. We sincerely appreciate the effort you put into your article, and it helps us, too. Thank you for sharing this information.cms development

    ReplyDelete
  6. The fact that you provided this knowledge on your blog is quite beneficial. We genuinely appreciate the time and work you put into writing your article, which also benefits us. I appreciate you giving this knowledge.web development services

    ReplyDelete
  7. You have given me a very complete post about. I and those who like it think it's a fantastic piece. Your sharing of this information with us is greatly appreciated.electronic signature

    ReplyDelete
Previous Post Next Post