There are some stages under which a Servlet is executing by the web container which is called as Servlet life cycle, that means web container maintains the life cycle of a Servlet which is as follows:
The init() method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started. When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
public void init() throws ServletException { // Initialization code... }
The service() method provides the service to the client(browser). The web container calls the service() method to handle requests coming from the client( browsers). Each time the server receives a request for a Servlet, the server creates a new thread and calls service() method. The service() method calls doGet() , doPost(). The general form is :
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // business logic }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
The web container calls the destroy() method before removing the Servlet instance from the service. It clean up the resources like memory, thread etc. The general form of the destroy() method is:
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
public void destroy() { // Finalization code... }
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc