Servlet Life Cycle With Example

The Servlet Life Cycle is the entire process of its creation until the destruction. servlet web container maintains the servlet lifecycle.
Servlet Life Cycle

Servlet Life Cycle Diagram

Three methods are central to the life cycle of a servlet.These are init(),
service() and destroy().They are implemented by every servlet and are invoked at a specific time by the server.

Read: Servlet API in Java

What are the phases of Servlet life cycle?

The servlet life cycle contains five phases:

1) load a servlet class-

The class Classloader is responsible to load servlet class.ClassLoader object is designed to load a class just once. It is loaded, when the first request for the servlet is received by the web container.

2) Servlet instance is created-

At the time code for a servlet is loaded, the server creates a single instance. That single instance handles every request made of the servlet. The servlet object is created once in the entire servlet life cycle.


3) init() method-

init() method is called after creating the servlet instance. It is called only once in the entire lifecycle. It is used to initialize the servlet. Init() is guaranteed to be called and completed before the servlet handles its first request. During init() method a servlet may want to read its initialization(init) parameter.

4) service() method-

Service() method is called every time when a request for a servlet is received.
Service() method is used to handle requests as appropriate for the servlet. The service() method accepts 2 parameters: a request object and a response object.
It overrides doGet() and doPost() method.
doGet() method - doGet() method is used to handle the get request.
doPost() method - doPost() method is used to handle the Post request.

Read more about HTTP Request method:
 HTTP Request methods - doGet(), doPost(), doHead(), doDelete() etc.

5) Destroy() method-


This method is called only once in the entire life cycle of a servlet. The servlet calls the destroy() method after the servlet has been taken out of service and all pending requests have completed or timed out.

Servlet Life Cycle Program:

ServletLifeCycle.java

Servlet Life Cycle Program
Servlet Life Cycle Program                                                                   

Web.xml

web.xml file of servlet life cycle
web.xml


Servlet Life Cycle With Example Servlet Life Cycle With Example Reviewed by Prashant Srivastava on October 13, 2018 Rating: 5

No comments:

Powered by Blogger.