Advanced Java Programming - Old Questions

3. What is servlet? Differentiate it with JSP. Discuss life cycle of servlet in detail.

10 marks | Asked in 2071

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.


Difference between servlet and JSP


Servlets

JSP

Servlet is a pure java code.

JSP is a tag based approach.

We write HTML in servlet code.

We write JSP code in HTML.

Servlet is faster than JSP.

JSP is slower than servlet because it first translate into java code then compile.

Writing code for servlet is harder than JSP as it is html in java.

JSP is easy to code as it is java in html.

Servlet can accept all protocol requests.

JSP only accept http requests.

Modification in Servlet is a time consuming task because it includes reloading, recompiling and restarting the server.

JSP modification is fast, just need to click the refresh button. (reloading, recompilation and restart the server is not required)

Servlets do not have implicit objects.

JSP does have implicit objects.

In Servlet, we can override the service() method.

In JSP, we cannot override its service() method.

In MVC pattern, servlet act as a controller.

In MVC, JSP act as a view.

In Servlet, by default session management is not enabled we need to enable explicitly.

In JSP, session management is automatically enabled.

Packages are to be imported at the top of the servlet.

Packages can be imported anywhere in the JSP code.


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 servlet. This 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.