Programs

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.

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.

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.

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

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.

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.

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.

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

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.

Want to share this article?

Land on Your Dream Job

Leave a comment

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

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks