A servlet life cycle is categories into five levels:
1) Loading of Servlet
2) Creating instance of Servlet
3) Invoke init() once
4) Invoke service() repeatedly for each client request
5) Invoke destroy()
Description of servlet life cycle
Level 1: Loading of Servlet
The servlet container deploys and loads all the servlets when the web server (for example, Apache Tomcat) starts up.
Level 2: Creating instance of Servlet
The servlet container produces instances of each servlet class until all of the servlet classes has load. Moreover, The servlet container only generates one instance of each servlet class, and all servlet requests are handle from the same servlet instance.
Level 3: Invoke init() method
The init() method is call for each instantiate servlet until all of the servlet classes have instantiate. On the other hand, The servlet is initialize with this form. Moreover, In the deployment descriptor (web.xml) file, you can define those init parameters.
Syntax
public void init(ServletConfig config) throws ServletException
Level 4: Invoke service() method
When a servlet request is receive, the web server creates a new thread that calls the service() function. Moreover, If the servlet is GenericServlet, the request is handle directly by the service() process; if the servlet is HttpServlet, the request is receive and dispatch to the appropriate handler method based on the request form.
Syntax
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
Level 5: Invoke destroy() method
When the servlet container shuts down (which normally occurs when the web server is stop), it unloads all of the servlets and calls the destroy() method on each one that has been initialize.
Syntax
public void destroy()
Interested in learning about similar topics? Here are a few hand-picked blogs for you!