Learn Servlet Lifecycle in Few Minutes

Servlet Lifecycle:-

Servlet Lifecycle

In this article, we going to learn regarding the Servlet lifecycle. This is a very important topic in Servlet. The Web container maintains the life cycle of a servlet class. To understand the lifecycle of a servlet. I have developed one web application with the following requirement:

  • I have written two servlets with the name HelloServlet and HaiServlet.
  • I have written one listener with the name HelloListener.
  • I have written one filter with the name HelloFilter.
  • I configured all the above components in the web.xml.
  • I also configured context parameters and config parameters for the HelloServlet.
  • I specified <load-on-startup> for the HelloServlet.

Sample web.xml

<web-app>

<context-param>

<param-name>state</param-name>

<param-value>Delhi</param-name>

</context-param>

<servlet>
<servlet-name>hello</servlet-name>

<servlet-class>com.xadmin.HelloServlet</servlet-class>

<init-param>

<param-name>city</param-name>

<param-value>Noida</param-name>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>hello<servlet-name>

<url-pattern>/hello.xadmin<url-pattern>

</servlet-mapping>

<servlet>
<servlet-name>hai</servlet-name>

<servlet-class>com.xadmin.HaiServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>hai<servlet-name>

<url-pattern>/hai.xadmin<url-pattern>

</servlet-mapping>

</web-app>

After deploying the above-said application on a server:

I did the following task:

  • Started the server
  • Send the request to HelloServlet.
  • Send the request to HaiServlet.
  • Shutdown the server.

Explain the things happening at every task

Case-1 Started the server

  1. Container reads information from web.xml and stores in the main memory using SAX parser(class loader used to read XML). If any problem happened while reading the web.xml container will not be ready to receive the request from the server.
  2. Container creates ServletContextObject and initializes the context object with context parameters specified in the web.xml.
  3. Container creates the thread pool.
  4. All the listener configured in the web.xml will be initialized (it is java class loading, creating an instance, initialization, and installation.
  5. All the filters configured in the web.xml will be initialized.
  6. Container checks whether any servlet is configured with <load-on-startup> tag. If anyone or more servlets found with <load-on-startup> tag then those servlets will be initialized by the container at container startup with the given priority by doing the following tasks.
  • Container loads the Servlet class into the main memory.
  • Container creates the instance of the servlet by invoking default constructor.
  • Container creates a servlet config object and initializes the config object with the config parameters specified in web.xml
  • Container associates the servlet context object with a servlet config object.
  • A container invokes the init() method by passing the ServletConfig object as a parameter to initialize the servlet instance with required resources.

Case-2 Send the request to HelloServlet.

  1. Container collects the URL pattern of the incoming request(/hello.jtc) and checks whether the corresponding servlet is initialized or not.
  2. If the servlets are initialized then container picks and thread from the thread pool and handovers the remaining request processing.
  3. Threads start request processing by doing the following tasks:
  • ServletRequest object will be created and will be initialized with the data coming from the client along with HttpRequest.
  • HttpServlet response object will be created and will be initialized with a response stream.
  • Service() method will be invoked by passing ServletRequest and servletResponse object as parameters.
  • Once service() method is executed then the response stream will be flushed to the client over the network and destroys the request and response object.
  • Once the response is delivered to the client, a thread will be returned to the pool.

interface–> ServletRequest
interface–> HttpServletRequest
interface–> HttpServletRequestImpl
ServletRequest sreq= new HttpServletRequestImpl();
servlet(sreq);

Case 3 Send the request to HaiServlet

  1. Container collects the URL pattern of incoming and checks whether the corresponding servlet is initialized or not.
  2. If the servlet is not initialized then container initializes that servlet by doing the following tasks:
  •  Container loads the Servlet class into the main memory.
  •  Container creates the instance of the servlet by invoking default constructor.
  •  Container creates a servlet config object and initializes the config object with the config parameters specified in web.xml
  •  Container associates the servlet context object with a servlet config constructor.
  •  A container invokes the init() method by passing the ServletConfig object as a parameter to initialize the servlet instance with required resources.

3. if the servlet is already initialized then container picks one thread from the thread pool and handovers the remaining request processing.

4. Threads start request processing by doing the following tasks:

  • Servlet request object will be created and will be initialized with the data coming from the client along with HttpRequest.
  • HttpServlet response object will be created and will be initialized with a response stream.
  • Service() method will be invoked by passing ServletRequest and ServletResponse object as parameters.
  • Once service() method is executed then the response stream will be flushed to the client over the network and destroys the request and response object.
  • Once the response is delivered to the client, a thread will be returned to the pool.

Case-4 Shutdown the Server.

At Container shutdown time, Following tasks will happen.

  1. Thread pool will be destroyed.
  2. All the servlets will be destroyed one by one. For destroying one servlet instance, the container invokes the destroy() method on the servlet instance.
  3. All the listeners will be destroyed.
  4. If any session object (private object for use) running in the container those also will be destroyed.

Servlet Lifecycle Methods:

There is three life cycle method of a Servlet.
  1. init()
  2. service()
  3. destroy()

init() method: The web container calls the init method only once after creating the servlet instance. It is used to initialize the servlet class. This method is of Javax.servlet.Servlet interface.

The syntax of the init method:
public void init(ServletConfig config) throws ServletException

service method(): The web container calls the service method whenever the request for the servlet is received. This method is meant to do the actual task of the servlet.

The syntax of the service method:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

destroy method(): The web container calls the destroy method before removing the servlet instance from the service. It is used for the cleanup purpose of the resource.
The syntax of the destroy method:
public void destroy()

Question and Answer

Q-1) when servlet will be initialized?

Ans: it will be initialized at container startup when you write <load-on-startup> tag. When you are not writing <load-on-startup> tag then servlet will be initialized when you send the first request.

Q-2) What steps will happen when a container is initializing servlet?

Ans- Refer Servlet Life cycle

Q-3) what is the importance of the number which you are providing for <load-on-startup>tag and what are the valid values?

Ans- Number represents the priority for initializing the servlet at container startup valid values are 0 to any +ve integer.

Q-4 How many times init() will be called in the servlet life cycle?

Ans- Only once

Q-5 Can I write the argument constructors in servlet class?

Ans- Yes, you can write argument constructors but the container always creates the instance with a Default constructor.

Q-6 How many times service() will be called in the servlet life cycle?

Ans- Many times, depending on the no.of request coming to the servlet.

Q-7 How many times destroy() will be called in the servlet life cycle?

Ans- only once at container shutdown time.

Q-8 How can I access config parameters and context parameter in the service() method?

Ans- // 1. config parameters
ServletConfig sc= getServletConfig();
sc.getInitParameter(“email”);
//2 context parameters
ServletContext ctx= sc.getServletContext();
ctx.getInitParameter(“phone”);

Q-9 what is the use of init() and destroy()?

Ans- init() is used to initialize the servlet instance with the required resources.
Destroy() is used to clean up the resources which are initialized by init().

Q-10 How many instances will be created for one servlet?

Ans: Container creates one or more servlet instances depending on the servlet model you are using.

Conclusion:

In this article, we learned regarding the Servlet lifecycle and its three methods. This method controls the flow of the servlet class. Please, feel free to drop a comment in the below comment box, if you find any doubt regarding the topic or you want to share more information about the topic. Happy Learning!

READ NOW :- introduction of servlets

Leave a Reply

Your email address will not be published. Required fields are marked *