Servlet Life Cycle

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

When a client computer sends a request to a server, in simple terms, when you type in a URL on your browser, the request ultimately reaches another computer, the 'server', which serves the particular web page you requested.

Servlet is a program that runs on that web server that can process your request and send the right content back. These programs have a life cycle from creation to destruction.

Introduction to Servlet

When we search on google for scaler.com, we make a request to a server to render the web page of Scaler. Handling such requests and rendering web pages dynamically can be done using Java Servlets.

So what exactly are servlets? Java Servlets (also known as Jakarta Servlets) are server-side programs that run on a web server, acting as a middle layer between client requests and database/applications on the web server.

They are used to host web applications on servers and mostly support all client-server protocols. The architecture of the servlet is as follows:

architecture of servlet

Client/Browser: The client through the browser sends HTTP requests to the webserver.

Web Server: Includes several components to control access to files hosted on the server. A basic HTTP server will comprehend URLs and follow HTTP protocol to deliver the contents of hosted websites.

Web Container: This is a web server component that interacts with Java servlets. It manages the servlets' life cycle, including loading, unloading, managing request and response objects, and URL mapping on the server-side. Ex- Tomcat.

Servlet Life Cycle

Servlet Life Cycle can be described as a series of steps that a servlet goes through during its life span from loading to destruction.

The Servlet Life Cycle is as follows:

  • Servlet class is loaded first when the Web container receives a new request.
  • Then the web container creates an instance of the servlet. This instance is created only once in the whole Servlet Life Cycle.
  • The servlet is initialized by the calling init() method.
  • service() method is called by the servlet to process the client's request.
  • Servlet is destroyed by calling the destroy() method.
  • Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.

Let us see the signature for each of the methods mentioned above:

init()

Whenever a user invokes the URL associated with the particular servlet, the init() method is called. It is called only once and not each time there is a request. An instance of a servlet is created through the init() method. Each user request creates a new thread catering to GET and POST requests.

service()

The web container calls the service() method each time there is a new request to the servlet. This is done by spawning a new thread. This method checks the HTTP request type, i.e, whether it is a GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods as per the request.

destroy()

This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the clean-up activities including closing database connections, halting background threads, etc. Then it removes the servlet from the container.

Architecture Diagram of the Servlet Life Cycle in Java

The following represents the Servlet Life Cycle. When a request is sent for a particular web page, the servlet corresponding to it must be initialized. The servlet container/web container will load the servlet and create an instance of it through init().

All the subsequent requests to the same web page will result in invoking the service() method. This method will typecast the ServletRequest and ServletResponse objects to HttpServletRequest and HttpServletResponse objects respectively. Servlets can handle multiple requests concurrently since each request results in a new thread.

The destroy() method is only called once all threads within the servlet's service methods have exited or after a timeout period.

Architecture Diagram of Servlet Life Cycle in Java

Program Illustrating Java Servlet Implementation

A program illustrating Java Servlet implementation We can implement a Servlet in the following ways:

  1. By implementing Servlet interface
  2. By extending GenericServlet class
  3. By extending HttpServlet class

The easiest and most common way is to extend HTTPServlet class. Let us see a Hello World program of a servlet using this method.

The HttpServlet class is extensively used to create servlet since it provides methods to handle HTTP requests like doGet(),doPost, doDelete() etc. The above code is used to display HTML content on the web page displaying "Hello World".

Features of Java Servlet Life Cycle

1. Portable

Its portability comes from the fact that Java is portable. This means that the Java code is compiled into bytecode. The bytecode is platform-independent. Hence it is Write Once Run Anywhere(WORA).

2. Efficient

Efficient because it creates a new thread for each request and not each process.

3. Scalable

Since Servlets can handle multiple requests due to multithreading, it is scalable to be quite responsive. Servlets are also amenable to various load distribution architectures. We can scale the web applications easily with the right load distribution.

4. Robust

JVM handles all the Servlet programs, including garbage collection and prevention of memory leaks.

Java Servlet Request

The job of a servlet is to handle the request sent by the client and reply with a response. To handle the client request, Java provides two interfaces named ServletRequest and HTTPServletRequest. Both these interfaces have several methods which can allow us to get information in the request. Let us see the various interfaces of HTTPRequest.

1. HTTP Request Header

HTTP Request header is used to pass additional information about the client/requestor to the server. These include extra information, metadata that the server can use. HTTPServletRequest provides getHeaderNames() and getHeader() methods which can be used to extract header names and header values, respectively. Let us see some of the common header names sent:

Accept: This specifies the acceptable media types in the response.

Accept-Charset: This indicates the acceptable character sets in the response. E.g., ISO-8859-1

Accept-Encoding: This restricts the content-coding values that are acceptable in the response.

Accept-Language: This restricts the set of language that is preferred in the response.

Authorization: This type indicates that the user agent is attempting to authenticate itself with a server.

User-Agent: This type contains the information about the user agent originating the request.

Content-Length: for POST messages, the length of data attached.

Cookie: From the Email address of the requester. Only used by custom clients, not by browsers.

Host: Host and port as listed in the original URL.

2. HTTP Request Parameters

HTTP Request parameters are ways in which clients can send user information to the server. Parameters can be sent in the URL or even in the request body. Any word after the '?' in a URL contains parameters. For Example: www.site.com?myparam1={id1}&myparam2={id2} myparam1 and my param2 are the parameters in the above URL request. We can access the parameters from a request in the following way using getParameter().

Typically, if an HTTP GET request is sent, the parameters are included in the query string in the URL. Whereas, if it is an HTTP POST request, the parameters are included in the body part of the HTTP request.

3. HTTP Request InputStream

An HTTP Post request can have a lot of data sent to the server in the request body. We can access all these data using InputStream pointing to the request body.

This will return the raw data from the request which can be separately parsed and used as necessary.

4. HTTP Request Context

An object of ServletContext is created by the web container when deployed. This object can be used to get metadata about the web application which is stored in the web.xml file.

As you can see, you have to first get the session object, to get access to the ServletContext object.

5. HTTP Request Session

A session can hold the details about a user between requests, across the application. An HTTPSession object is used for session management. When a new user accesses the application for the first time, the HTTPSession object is obtained through request.getSession().

The user is given a unique ID to identify the session. A particular session is active until a particular specified timeout value is mentioned in the web.xml file. Let us see the code snippet to create a session:

Session user information can be accessed/modified using setAttribute and getAttribute as follows:

Java Servlet Response

Let us explore the HTTP Response object which is used to send appropriate data from server to client.

1. HTTP Response Header

Headers in response must be set before writing data into it. You can set it as key-value pair in the following way-

2. HTTP Response Content Type

This is a header used to tell the browser, the kind of data being returned. The default for servlets is text/plain, but text/HTML is usually explicitly specified. This header can be set in the following way-

3. HTTP Response Content Length

Content length is used to tell the browser how many bytes are being sent by the servlet. This is needed only when the browser is using a persistent HTTP connection.

4. HTTP Response Write HTML

In order to send HTML as response back to browser, we need to use PrintWriter.

5. HTTP Response Redirection

When we need to direct users to a location other than what is requested, redirection is used. This can happen when the document is moved pointing to a different location. We can do this by using the following code in doGet()/doPost() method:

Benefits of Servlets

Easy to implement

It is wasy to implement Servlet using Java APIs. It is also easy to implement sessions and cookies since dedicated interfaces are provided for each use case.

Easy Database Connection

There was no way to connect to the database directly using CGI. But using Servlets, we can connect to the database directly and track sessions.

Protocol Independent

Servlets are flexible to follow any web protocol including FTP, HTTP.

Better Exception Handling

Earlier, CGI(Common Gateway Interface) scripts which were used before Servlets and written in C++ did not have good exception handling, for instance, the application might crash if there was a divide by 0 error. Servlets, written in Java have much better ways to handle such exceptions and make sure the application doesn't crash. It has provisions for redirection and forwarding.

Security

The server-side components inherit the security of the webserver. And the Servlet programs benefit from Java's Security Manager.

Conclusion

  • Java Servlets are server-side programs to handle client requests to a web application through the browser, and respond.
  • Life Cycle of Servlet consists mainly of three methods - init(), service(), and destroy().
  • HTTP requests from clients/browsers can be read. This includes cookies, parameters, and session handling.
  • HTTP response from the server is sent can be sent to the client in various forms, including text, documents, HTML, binary, etc.
  • There are various inbuilt methods provided to handle requests and responses.
  • Servlets can handle multiple requests concurrently through multithreading. Each new request will spawn a new thread and hence will consume less space than each request creating a new process itself.
  • JVM's garbage collector handles stale data and prevents memory leaks.
  • Servlets are robust, make a connection to the database easy, and have better security management interfaces.