Servlet is used in J2EE to create the dynamic web pages under Java Environment. Like Applets, Servlet also have init() and destroy() methods. In this article i will explain the Life cycle of servlet.
Step 1 : After Compilation of the Servlet, the class file is loaded by the loader.
Step 2 : Then the Container instantiates the Servlet class by calling default Constructor. Read this article to know more that how container works for Servlet.
Step 3: At Step 2, the Servlet object is just normal java object. It is the init() method which is just called after the instantiation of object and gives the Servletness to object. Like applets, this method is called only once in life cycle. It is recommended not to override the init() method but if you want to override then read this article.
Step 4 : Then Service() method is called and this is the place where servlet spends most of its life. Each request here comes as a separate thread. This method then internally calls the doGet() or doPost() method depending upon the type of request comes.
Step 5 : destroy() method is called just before destroying the Servlet. This method should be used if any clean code needs to be run before destroying the servlet.
Leave a Reply