Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconServlet Life Cycle in Java: Methods, Architecture, Comparison & Setup

Servlet Life Cycle in Java: Methods, Architecture, Comparison & Setup

Last updated:
17th Aug, 2022
Views
Read Time
16 Mins
share image icon
In this article
Chevron in toc
View All
Servlet Life Cycle in Java: Methods, Architecture, Comparison & Setup

Introduction  

Servlets yield a method that is not only component-based and platform-independent but is also very much supportive for building web-based applications. Servlets have access to the java APIs and JDBC API to access databases. In the case of Java Servlets, although there are no restrictions in terms of the performance of the CGI (Common Gateway Interface) program, there still exist some disadvantages. 

The Servlet container manages the whole Servlet life, and it uses the javax.servlet.Servlet interface. This interface understands the Servlet object and also manages it. Hence, before creating a Servlet object, it is vital to understand the servlet life cycle that explains how the Servlet container handles the Servlet object.

Check out our free courses to get an edge over the competition.

What is Servlet?

Servlet is a technology that is very much beneficial for creating dynamic web pages. It acts as an intermediate layer between the web browser and HTTP clients or servers. With the help of servlets, at first, we collect the inputs from the users and then create web pages dynamically. Servlet extends the capabilities of servers and host applications. Servlets extend the capabilities of the servers and also respond to any type of requests for users.

Ads of upGrad blog

Check out upGrad’s Java Bootcamp

Source

CGI vs Servlets

Before servlets, CGI was used broadly. CGI is a way to pass the request received from the user to an application program. Although CGI is a way for a web server, it also gets the response from the browser (client). When the user requests a web page to the browser, the server sends it back to them.

When a client wants to fill out a form on a web page and try to send it again, it gets processed by the application program. The server passes the information to a small web application program. This program first processes the data and then sends it back via a confirmation message.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Servlet Life Cycle Methods in Brief

There are mainly three life cycle methods of a servlet, which we can describe as:

  1. init()
  2. service()
  3. destroy()

Source

Servlet Architecture

  • Firstly, it reads the data sent by clients. Then, it inserts an HTML form in a web page and then sends the requests sent by clients.
  • After that, the servlet processes the data and connects to a database management system, executing RMI by invoking web services.
  • After processing, the documents can be sent in text and gif formats.
  • Finally, it sends the HTTP to the client.

Source

Now we will discuss these methods in details

Stages of the Servlet Life Cycle:

The servlet life cycle chiefly goes through the following stages:

 Loading a Servlet

  1. Initializing the Servlet

iii. Request handling

  1. Destroying the Servlet

 Let’s go through the details of these stages:

 Loading a Servlet:

The first stage of the life cycle of servlet loads and initializes the Servlet using the Servlet container. The Servlet Container or Web container can load the Servlet at any of these two stages:

  1. a) Initializes the context on configuring Servlet using a zero or positive integer value.
  2. b) If the Servlet doesn’t exist in the stage, it might delay the loading procedure until the Web container decides that the particular Servlet is required to serve a request.

At this stage, the Servlet container does two operations:

  • Loading: This stage of the life cycle of servlet in java loads the Servlet class.
  • Instantiation: This stage creates the Servlet instance. The container uses the no-argument constructor to create the Servlet’s new instance in the life cycle of servlet.

 Initializing a Servlet: Once the Servlet is instantiated, the Servlet container will initialise the instantiated Servlet object. It does this by calling the Servlet.init(ServletConfig) method that accepts ServletConfig object reference in the form of parameter.

The Servlet container calls the Servlet.init(ServletConfig) method only once, instantly after the Servlet.init(ServletConfig) object is successfully instantiated. Moreover, this method can initialize the resources like the JDBC data source.

If the Servlet fails to initialize, it notifies the Servlet container by raising the ServletException or UnavailableException.

The init() method is called only once after the servlet instance is created. At first, it initialises the servlet. Servlet. init() indicates that the servlet instance was created successfully.

Servlet container calls the Servlet.init() method to denote that this Servlet instance is successfully instantiated and is ready for the service.

  Syntax of init() method is given as :

public void init(ServletConfig config) throws ServletException {

           //initialization code

}

iii. Handling request: After initializing a Servlet, the Servlet instance is prepared to handle the client requests. When the Servlet instance is found to serve a request, the Servlet container does the following operations:

It creates the ServletResponse and ServletRequest objects. If this is found as an HTTP request, the Web container creates HttpServletResponse and HttpServletRequest objects which are the subtypes of the ServletResponse and ServletRequest objects, respectively.

After making the request and response objects, the Servlet.service(ServletRequest, ServletResponse) method is called by passing the request and response objects.

When processing the request, the service() method may raise the IOException, ServletException, or UnavailableException.

service()

Whenever the servlet receives the request, the web container calls the service() method.

  • To collect the data requested b
  • y the client, the service request object is used.
  • To generate the output content, the ServletResponse object is used.
  • To inform the Servlet regarding the client’s requests.

Signature of service() method is given as:

public void service(ServletRequest request , ServletREsponse response)

            throws ServletEXception , IOException {

          //request handling code

}

The service() method uses doGet, doPost, doPut, doDelete and many other methods.

  • Using the ServletRequest object in servlet life cycle in java, this method collects the data requested by the client.
  • Using the ServletResponse object, this method produces the output content.
  1. Destroying a Servlet: When a Servlet container agrees to destroy the Servlet, it does the following operations:

It allows all the currently operating threads in the service method of the Servlet instance to accomplish their jobs.

After operating threads have finished their jobs, the Servlet container invokes the destroy() method located on the Servlet instance.

When the execution of destroy() method completes, the Servlet container frees up this Servlet instance’s all references. Hence, it becomes qualified for garbage collection.

destroy()

The user calls the destroy() method at least once in a life cycle of a servlet. It is used to terminate database connection, to release the allocated memory and resources. It also helps in clean-up purposes, and garbage collection is associated with this.

What makes the destroy() method stand out from other servlet life cycle methods is that it operates only once throughout the Servlet’s lifetime. Moreover, it indicates the Servlet instance’s termination. When the destroy() method is triggered, the Servlet container frees up the Servlet instance.

The signature of the destroy() method  is

public void destroy(){

      // Finalization code

}

Also Read: Servlet vs JSP

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

How are Servlet Life Cycle Methods called?

The method that servlet containers implement for servlet life-cycle events is called servlet life cycle methods (also called container callback methods).

In servlet workflow and architecture, we discussed how the servlet containers perform different operations on the servlet components. Let’s check what happens when the first request is provided to the servlet component with reference to the servlet life cycle methods.

  • The Servlet container prepares one set of ServletResponse and ServletRequest objects for the current request.
  • The Servlet container loads the Servlet class from the WEB-INF/classes folder and instantiates that object through the 0-param constructor.
  • The Servlet container creates an instantiation event and calls init(ServletConfig cg) method on the servlet class object. This servlet class object will be assigned with the ServletConfig object.
  • Servlet container starts/create one thread specifying the current request and raises “request processing event”.
  • Servlet container calls the service(ServletRequest req, ServletResponse resp) method on the servlet class object.
  • The service(-,-) method delivers the generated output to the browser using the web server and response object.
  • The Servlet container destroys the thread which was created for the current request. Also, it destroys the ServletRequest, ServletResponse objects of the current request.

Explore our Popular Software Engineering Courses

Servlet Life Cycle Events:

The life cycle of servlet in java has the following events:

 Servlet Instantiation Event:

This event is raised when the servlet container creates the servlet class object. It is only raised once for a servlet component.

Request Processing Event:

It is raised when the servlet container prepares the servlet class object to process the request. Moreover, it is raised for every request.

Destruction Event:

It is raised when the servlet container is ready to destroy a servlet class object. It is raised only once for a servlet component.

 What happens if the main(-) method is placed in the servlet component?

The Servlet container implements the servlet component using the methods of the servlet life cycle in java. The main(-) method is not a life cycle method. Hence, it will not be executed in the servlet life cycle. But it will be executed only if it is explicitly called from any servlet life cycle method; otherwise, it will be considered an ordinary method.

Environment Setup of a Servlet

To create a Servlet application, at first, we need to follow some steps like installing Tomcat Server, which gets described below-

1. Creating a Directory Structure 

Source

First, we need to create the above directory structure inside a directory named Apache – Tomcat\webapps directory. We need to keep all HTML, static files, images under the web application creating a folder. The servlets must be kept in the class folder. Lastly, the web.xml file should be under the WEB-INF folder.

2. Creating a Servlet

There are three different ways by which we can create a servlet.

  1. By implementing the Servlet interface.
  2. By extending the GenericServlet class.
  3. It is necessary to extend the HTTP servlet class.

A servlet can be mainly formed if we can extend the httpServlet abstract class.

In-Demand Software Development Skills

3. Compiling the Servlet

For compiling the servlet, a JAR file is required –

  1. By setting the classpath.
  2. By pasting the jar in JRE/lib/ext folder.

4. Create Deployment Descriptor

DD can be defined as an XML file that is used by web-based servers so that

they can run servlets with ease. DD is used for several important purposes.

  1. By mapping the URL to the Servlet class.
  2. By initialising parameters.
  3. By defining the Error page.
  4. By security roles.
  5. By declaring tag libraries.

5. Start the Server

To start the Apache Tomcat server, we need to double click on the startup.bat file under apache-tomcat/bin directory, and it will start working.

6. Starting Tomcat Server for the First Time

To start Tomcat Server for the first time, we need to set JAVA_HOME in the Environment variable. The following steps are mentioned below. Right Click on My Computer, and we need to go to Properties.

Source

  1. Next, we will go to Advanced Tab, and we need to click on the Environment Variables button.

Source

  1. Therefore, we will click on the New button and enter JAVA_HOME inside the Variable name text field and the path of JDK inside the Variable value text field. Then, we need to save it by clicking, OK.

Source

7. Running the Servlet Application

When we run the servlet button, it will look like –

After opening the browser, we need to type http:localhost:8080/First/hello

Checkout: Java Developer Salary in India

Servlet Request Interface

ServletRequest aims to supply the client with authentic pieces of information about a servlet that

includes content type, length, parameter values, and many more.

Methods 

1. getAttribute(String)

Returns the value of attributes as requested, if attributes have no existence

then returns NULL.

2. getAttributeNames()

It returns the names of the present attributes that are requested by the clients.

3. getCharacterEncoding()

Returns some set of characters.

4. getContentLength()

Returns the requested data entity size.

5. getContentType()

At first, it requests the object’s identity. If not found, it returns a NULL value.

6. getInputStream()

Returns a binary stream of data received by the client and then returns the strings.

7. getParameter(String)

Returns a string of the parameters.

8. getParameterNames()

It returns the parameter names.

9. getParameterValues(String)

It returns the values of the parameters. They always exist in the form of a string.

10. getProtocol()

It returns the protocol and version in the form <protocol>/<major version>.<minor version>.

11. getReader()

It returns a buffered reader to read the text in the request body.

12. getRealPath(String)

avoids the virtual path and returns the real path.

13. getRemoteAddr()

It returns the IP address.

14. getRemoteHost()

It returns the completely structured hostname of the agent.

15. getScheme()

It returns the URL used in the request.

16. getServerName()

It returns the hostname of the server.

17. getServerPort()

It returns the port number.

18. setAttribute(String, Object)

This method accumulates an attribute for any kind of requests.

Explore Our Software Development Free Courses

Servlet Response

ServletResponse invokes an object, and the response of various users is recorded. The web container is responsible for all these activities. The step to create this is very much important. The step is to create an object.

Now let us talk aboutServletConfig and ServletContext below in detail.

ServletConfig

1. Web container creates the config object based on the initialisation parameters.

2. One ServletConfig per Servlet must be present.

Methods

1. Equals(Object)

checks if the current object has equal value with the given object.

2. GetHashCode()

Works as the default hash function.

3. GetType()

Returns the Type of the current instance.

4. MemberwiseClone()

If we invoke this object, a shallow copy can be created. It refers to the present object by default.

5. ToString()

Returns a string, which represents the current object.

ServletContext

Let us discuss ServletContext below:

  1. It is very much necessary to make the reference object accessible to each and every Servlet of the web application.
  2. The reference object is actually the runtime implementation of these.

The two types of servlets can be defined as:

1. Generic Servlets 

We refer to the Generic servlets as independent of protocols, and also, it is required to invoke it by overriding. We can invoke generic servlets in three ways –

  • HTML File 

    We can create a very uncomplicated HTML file that can look like WebContent/index.html.

  • Java Class File 

A generic servlet can be created by extending the GenericServlet class. If we can create a simple new class file, then we can rename it as generic. The file path looks like:/  javaResouces/src/default package/generic.java.

  • XML File 

    We can find this file in the path WebContent/WEB-INF/web.xml. We can map the servlet with a specific URL.

2. HTTP servlet 

This type of servlets is nothing but an extension of Servlet classes. Though it is HTTP dependent, it sets some rules which help the web browser and servers to communicate, and the HTTP servlet can also override doGet() or doPost() methods. Also, it can override both methods.

Advantages of Servlets

Now let us see some advantages of servlets –

  1. Performance is outstanding.
  2. Servlets can execute within the address space of a server. As a result, we can say that it is unnecessary to create a separate address space to handle the client request.
  3. They are platform-independent and mainly component-based.
  4. Servlets are secured as the security manager sets some restrictions to protect the resources and data.
  5. While working, users don’t need to worry about freeing memory as a garbage allocation technique.
  6. Servlets provide full functionality as all the libraries are available. It can easily communicate with applets and other mechanisms.

Source

Disadvantages of Servlets

The limitations of servlets are discussed as –

  1. Only one servlet can be loaded in the JVM at a time. So, we can say that it matters about the number of requests.
  2. When there is a request, there can be a thread only. No process should be present there.
  3. Designing a servlet is costly, and sometimes, it is quite problematic.
  4. We need other setups in the browser like JRE (Java Runtime Environment) on the server to run servlets.

Also Read: Java Project Ideas & Topics

Ads of upGrad blog

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

In this modern era of the digital world, technology and the internet have become the driving force of all. The internet is restless. Each and every second, it is busy to transfer large amounts of data.

But due to the bulk transfer of data, the internet slows down, as we need speed also. So, the dynamic sites get created by software developers. These sites get changed and updated at every moment. To know further about the Servlets in Java and development, check out upGrad’s Executive PG Program in Full-stack Software Development and kick start your journey.

The main motive of this article is to provide the readers with a basic concept of servlets so that they can obtain a fundamental idea about servlets.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are servlets in Java?

The servlet API is the foundation for server-side Java. It enables Java code to run on the server (as opposed to the browser) and interact with HTTP requests to deliver content and manipulate data, much like a CGI script. In other words, they are just chunks of code that your web server can run to provide dynamic content. Servlets are typically used to provide dynamic content, such as a page of search results or a chat room. Servlets are Java objects which extend the HttpServlet class. They are used to build web applications and the HttpServlets are the ones which are used by the web server to deliver JavaServer Pages.

2What is a servlet life cycle in Java?

The Servlet life cycle is divided into four distinct phases: 1. init() - This is a special method where initialization can be done. For example, you can create database connections, fetch information from your database during this phase. When you do this, you're doing a little bit of bootstrapping. This is a safe place to do this since you don't want to do any initialization more than once (since the container will destroy the servlet if it starts a new instance). 2. service() - This is the phase where you do the work. In a servlet, you can do get requests, generate dynamic content and send it back to the user. This is the phase where you process the request and write your response back to the user. 3. destroy() - This is where the servlet is going to be destroyed. This is where you need to do any cleanup. For instance, you might want to close your database connections in this phase. 4. shutdown() - This is the last phase where you can close everything else. For instance, you can stop a timer, release any other resources, etc.

3What is the servlet architecture?

In the servlet architecture, a servlet is an application component that generates dynamic content for an HTTP web server and an HTTP browser. A servlet is a Java program that receives requests from the HTTP server and sends back responses. A servlet is a small program that runs within the container and provides various services to the applications. A servlet can be written in Java or in JSP and it is with the help of a servlet that the JSP technology works. A servlet can be considered as the heart of a Java based web application.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31540
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46898
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901297
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
51958
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909107
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34714
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902365
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26109
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4320
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon