Set - 3

Question 1 :

Explain the life cycle of Servlet.

Answer :

Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.


Question 2 :

When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet?

Answer :

An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.


Question 3 :

Why don't we write a constructor in a servlet?

Answer :

Container writes a no argument constructor for our servlet.


Question 4 :

When we don't write any constructor for the servlet, how does container create an instance of servlet?

Answer :

Container creates instance of servlet by calling Class.forName(className).newInstance().


Question 5 :

Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?

Answer :

Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet's service() method to finish.