Advanced Java Programming - Old Questions

10. What is servlet? Discuss its life cycle.

5 marks | Asked in 2072

A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.


Life Cycle of Servlets

In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().



The client enters the URL in the web browser and makes a request. The browser then generates the HTTP request for this URL and sends it to the web server. This HTTP request is received by the web server. The web server maps this request to the corresponding servlet.

init():

-          The server invokes the init( ) method of the servletThis method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.

service():

-          The service() method is the main method to perform the actual task.

-          The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.

destroy():

-          Finally server unloads the servlet from the memory using the destroy() method to clean any resources.

-          The destroy() method is called only once at the end of the life cycle of a servlet.