What is Servlets? Explain about life cycle of a servlet.
Debashis Maharana, Aug 10/2019
Servlets is a Java based web technology from Sun Microsystems. It is a Java EE technology. It is an API.
On the other hand, a servlet is a web server side piece of code that enhances the functionality of the web server. A servlet is a dynamic web resource.
A servlet is a servlet container managed public Java class that implements javax.servlet.Servlet interface. Servlet interface is a web component contract between the web component and the web container.
The following code gives the general structure of a servlet:-
destroy() are abstract methods of Servlet interface. Whenever something happens in the life of the servlet, Servlet engine calls these methods implicitly (automatically) and hence these are known as Life Cycle methods.
A user defined servlet class has 4 life cycle phases:-
- Instantiation phase
- Initialization phase
- Servicing phase
- Destruction phase
Servlet engine loads user defined servlet class from secondary memory into primary memory dynamically. Servlet engine creates the instance of loaded servlet class with methods of Reflection API.
During instantiation phase, a servlet is missing with 2 pieces of information:
- Context information
- Initial configuration information
When the above informations are not available even though servlet object is ready, it doesn’t possess complete servletness. Servlet engine creates ServletConfig interface object and encapsulates the above missing informations in it. Now Servlet engine calls init(ServletConfig) by supplying ServletConfig object as argument. One’s init() is completely executed, initialization phase of the servlet is over and the servlet is ready to serve the client’s request.
The instantiation and initialization happens only one’s in the lifetime of a servlet.
Servlet engine creates ServletRequest interface object encapsulating the user input. Servlet engine creates ServletResponse interface object encapsulating client socket details. Servlet engine calls service method by supplying request and response object references as arguments.
Servlet engine calls service method of servlet for each client request.
When the web application is unloaded (undeployed), Servlet engine calls destroy()of the servlet and marks the servlet instance for garbage collection.