Servlet life Cycle–A simple overview

    0
    13
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share


    Mostly a Servlet is having 3 major stages.

    1. Initialization—-init() method
    2. Service——–service()method
    3. Destruction—-Destroy() method

    Init method:

    Init() is the method when a servlet starts and a servlet’s life cycle begins. It is called when server instantiated the servlet. The major advantage is ,it is called only once in its life cycle. Init method create or initializes all the required resources that will will be used during it’s life time.

    The Signature is —

    public void init(ServletConfig config) throws ServletException 

    it takes the ServletConfig object as a parameter and pass it to the super init method.

    super.init(config);

    So the structure of a init method looks like—

                public void init(ServletConfig config) throws ServletException {
                        super.init(config);
                         }

    The important aspect of this signature is that a init method can throw an exception ServletException.When it occures??? If the init method could not initializes all the required resources that will will be used during it’s life time.

    Service method:

    As picture depicts, once the init method is called , the second step is to call Service method. So Service method can not be called if the init method is not called. This methods actually talk to client ..i mean this method takes care of the request and response. We generally do not implement this method but if our servlet class is extended  to GenericServlet then we need to implement that.Service method support HTTP /1.1 and above.
    The method looks like-

                protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
       

    Destroy method:

    This method is the end of servlet’s life cycle.if we shut down a service , this method is automatically called. All the resources that were consumed by init method is released. This is kind of garbage collection of core java. Also some important aspect like closing database connection,closing file system or any important information if required for next run.
    The method looks like–
     public void destroy() 
    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here