Introducing Servlets
Servlets are small programs that execute on the server side of a web connection. A Servlet is a
Java program that runs on a web server (inside a Servlet container) and generates dynamic web
content (usually HTML, JSON, XML, etc.).
It acts as the middle layer between:
Client (Browser) → sending request
Server (Application + Database) → sending response
Servlet Architecture
Client (Browser) → HTTP Request → Web Server + Servlet Container
Servlet → Business Logic → Response
← HTTP Response ←
Web Server: Handles HTTP requests (e.g., Apache, Nginx, Tomcat)
Servlet Container: Runs Servlets, manages lifecycle, provides request/response objects (e.g.,
Apache Tomcat, Jetty, GlassFish)
Servlet API: Defines HttpServlet, ServletRequest, ServletResponse, etc.
HTTP Servlets Basics
HttpServlet is an abstract class in the Servlet API that simplifies creating servlets for HTTP-
based web applications.
Package: [Link] (Java EE 9+) or [Link] (older
versions)
Instead of writing the generic service() method from scratch, you override HTTP-
specific methods:
o doGet() → for HTTP GET requests
o doPost() → for HTTP POST requests
o doPut(), doDelete(), etc.
What is HTTP SERVLET?
A Java class that handles requests and responses over the HTTP protocol.
Runs inside a Servlet Container (e.g., Apache Tomcat).
Used for dynamic web content (opposite of static HTML pages)
HttpServlet Class In Java
HttpServelt is an abstract class, it comes under package '[Link]' . To
create a servlet the class must extend the HttpServlet class and override at least one of its
methods (doGet, doPost, doDelete, doPut). The HttpServlet class extends the GenericServlet
class and implements a Serializable interface.
Methods of HttpServlet Class
1. doGet() Method
This method is used to handle the GET request on the server-side.
This method also automatically supports HTTP HEAD (HEAD request is a GET request
which returns nobody in response ) request.
The GET type request is usually used to preprocess a request.
Modifier and Type: protected void
Syntax:
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the GET
request.
ServletException - Use to handle the GET request.
2. doPost() Method
This method is used to handle the POST request on the server-side.
This method allows the client to send data of unlimited length to the webserver at a time.
The POST type request is usually used to post-process a request.
Modifier and Type: protected void
Syntax:
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException
Parameter:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Throws:
IOException - if an input or output error is detected when the servlet handles the POST
request.
ServletException - Use to handle the POST request.
3. doHead() Method
This method is overridden to handle the HEAD request.
In this method, the response contains the only header but does not contain the message body.
This method is used to improve performance (avoid computing response body).
Modifier and Type: protected void
Syntax:
protected void doHead(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the HEAD
request.
ServletException - Use to handle the HEAD request.
4. doPut() Method
This method is overridden to handle the PUT request.
This method allows the client to store the information on the server(to save the image file on
the server).
This method is called by the server (via the service method) to handle a PUT request.
Modifier and Type: protected void
Syntax:
protected void doPut(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Throws:
IOException - if an input or output error is detected when the servlet handles the PUT
request.
ServletException - Use to handle the PUT request.
5. doDelete() Method
This method is overridden to handle the DELETE request.
This method allows a client to remove a document or Web page from the server.
While using this method, it may be useful to save a copy of the affected URL in temporary
storage to avoid data loss.
Modifier and Type: protected void
Syntax:
protected void doDelete(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the
DELETErequest.
ServletException - Use to handle the DELETE request.
6. doOptions() Method
This method is overridden to handle the OPTIONS request.
This method is used to determine which HTTP methods the server supports and returns an
appropriate header.
Modifier and Type: protected void
Syntax:
protected void doOptions(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the
OPTIONS request.
ServletException - Use to handle the OPTIONS request.
7. doTrace() Method
This method is overridden to handle the TRACE request.
This method returns the headers sent with the TRACE request to the client so that they can
be used in debugging.
Modifier and Type: protected void
Syntax:
protected void doTrace(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to the
client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the TRACE
request.
ServletException - Use to handle the TRACE request.
8. getLastModified() Method
This method returns the time the HttpServletRequest object was last modified.
If time is unknown the method will return a negative number.
This method makes browser and proxy caches work more effectively.
also reducing the load on server and network resources.
Modifier and Type: protected long
Syntax:
protected long getLastModified(HttpServletRequest request)
Parameter: request - an HttpServletRequest object that contains the request the client has
made of the servlet.
9. service() Method
This method receives standard HTTP requests from the public service method and dispatches
them to the doXXX methods defined in this class.
Modifier and Type: protected void
Syntax:
protected void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the HTTP
request.
ServletException - Use to handle the HTTP request.
10. service() Method
This method is used to dispatch client requests to the public service method.
Modifier and Type: public void
Syntax:
public void service(ServletRequest request,ServletResponse response)
throws ServletException,IOException
Parameters:
request - an HttpServletRequest object that contains the request the client has made of the
servlet.
response - an HttpServletResponse object that contains the response the servlet sends to
the client.
Exceptions:
IOException - if an input or output error is detected when the servlet handles the HTTP
request.
ServletException - Use to handle the HTTP request.
Example:
package [Link];
import [Link].*;
import [Link].*;
// here GFGServlet class inherit HttpServlet
public class GFGServlet extends HttpServlet {
// we are defining the doGet method of HttpServlet
// abstract class
public void doGet(HttpServletRequest rq,
HttpServletResponse rs)
// here user write code to handle doGet request
}
// we are defining the doPost method of HttpServlet
// abstract class
public void doPost(HttpServletRequest rq,
HttpServletResponse rs)
// here user write code to handle doPost request
} // class ends
Life Cycle of a Servlet
The entire life cycle of a Servlet is managed by the Servlet container, which uses
the [Link] interface to understand the Servlet object and manage it. So, before
creating a Servlet object, let's first understand the life cycle of the Servlet object, which is
actually understanding how the Servlet container manages the Servlet object.
Note: If you have worked with a servlet before, you must have used import [Link].*; but
with Jakarta EE 9, the package names changed to import [Link].*;
States of the Servlet Life Cycle
1. Loading a Servlet
The first stage of the Servlet lifecycle involves loading and initializing the Servlet. The Servlet
container performs the following operations:
Loading: The Servlet container loads the Servlet class into memory.
Instantiation: The container creates an instance of the Servlet using the no-argument
constructor.
The Servlet container can load the Servlet at one of the following times:
During the initialization of the web application (if the Servlet is configured with a zero or
positive integer value in the deployment descriptor).
When the Servlet is first requested by a client (if lazy loading is enabled).
2. Initializing a Servlet
After the Servlet is instantiated, the Servlet container initializes it by calling the
init(ServletConfig config) method. This method is called only once during the Servlet's life
cycle.
3. Handling request
Once the Servlet is initialized, it is ready to handle client requests. The Servlet container
performs the following steps for each request:
Create Request and Response Objects
The container creates ServletRequest and ServletResponse objects.
For HTTP requests, it creates HttpServletRequest and HttpServletResponse objects.
Invoke the service() Method
The container calls the service(ServletRequest req, ServletResponse res) method.
The service() method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.)
and delegates the request to the appropriate method (doGet(), doPost(), etc).
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it follows these steps which are listed
below
Allow Active Threads to Complete: The container ensures that all threads executing the
service() method complete their tasks.
Invoke the destroy() Method: The container calls the destroy() method to allow the Servlet
to release resources (e.g., closing database connections, freeing memory).
Release Servlet Instance: After the destroy() method is executed, the Servlet container
releases all references to the Servlet instance, making it eligible for garbage collection.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
init()
service()
destroy()
Servlet life cycle can be defined as the stages through which the servlet passes from its creation
to its destruction.
The servlet life cycle consists of these stages:
Servlet is created
Servlet is initialized
Servlet is ready to service
Servlet is servicing
Servlet is not ready to service
Servlet is destroyed
1. init() Method
This method is called by the Servlet container to indicate that this Servlet instance is
instantiated successfully and is about to put into the service.
Illustration:
// init() method
public class MyServlet implements Servlet {
public void init(ServletConfig config)
throws ServletException
{
// initialization code
}
// rest of code
}
Important Key Points about init() Method
A Servlet life begins from this method. This method is called only once to load the servlet,
Since it is called only once so the connected architecture code is written inside it because we
only want once to get connected with the database
Now the Question Arises Why can't we write connected architecture code inside the
constructor, since constructor also run only once in it's entire life?
Ans: Suppose if the connection doesn't get established, then we can throw an exception from
init() and the rest of the steps stop executing. But in the constructor we can't use, throw in it's
prototype otherwise it is an error
This method receives only one parameter, i.e ServletConfig object.
This method has the possibility to throw the ServletException.
Once the servlet is initialized, it is ready to handle the client request.
In servlet programs, we use non parameterized version of init().
Now the Ouestion Arises Why it is recommended to use the non parameterized version
of init() instead of parameterized version?
Ans: There are two approaches in order to answer this question. We are going to discuss
about both the approach one by one.
Approach 1: Using the Parameterized init([Link])
When the parameterized init(ServletConfig con) is called during the servlet life cycle, the
following steps occur:
First the overridden init(ServletConfig con) in our servlet class is executed.
Then the init(ServletConfig con) method in the parent HttpServlet class is called using
[Link](con).
Finally the init() (non-parameterized version) in the parent HttpServlet class is invoked.
However, this method has an empty body, making the call redundant.
public void init(ServletConfig con) throws ServletException
{
[Link](
con); // Calls HttpServlet's init(ServletConfig)
// Custom database connection code here
}
Disadvantages:
More Calls: Total 3 init() calls
Parameterized init(ServletConfig con) in our servlet class.
Parameterized init(ServletConfig con) in HttpServlet.
Non-parameterized init() in HttpServlet(empty body, hence useless)
Performace Overhead: Extra calls increase stack usage and execution time.
Approach 2: Using the Non-Parameterized init()
Instead of overriding the parameterized init(servletConfig con), override the non-
parameterized init().
During the servlet life cycle
The parameterized init(servletConfig con) in theHttpServlet class is called automatically.
This method then calls the non-parameterizedinit() method of our servlet directly.
public void init() throws ServletException
{
// Custom database connection code here
}
Advantages:
Fewer Calls: Total of 2 init() calls
Parameterized init(ServletConfig con) in HttpServlet.
Non-parameterized init() in our servlet class.
2. service() Method
This method is used to inform the Servlet about the client requests
This method uses ServletRequest object to collect the data requested by the client
This method uses ServletResponse object to generate the output content
Illustration:
// service() method
public class MyServlet implements Servlet {
public void service(ServletRequest req,
ServletResponse res)
throws ServletException, IOException
{
// request handling code
}
// rest of code
}
Important Key Points about service() Method:
This method provides the connection between client and server
The web server calls the service() method to handle requests coming from the client( web
browsers) and to send response back to the client
This method determines the type of Http request (GET, POST, PUT, DELETE)
This method also calls various other methods such as doGet(), doPost(), doPut(), doDelete()
This method accepts two parameters.
req is the ServletRequest object which encapsulates the connection from client to server
res is the ServletResponse object which encapsulates the connection from server back to the
client
3. destroy() Method
This method runs only once during the lifetime of a Servlet and signals the end of the Servlet
instance
Syntax:
// destroy() method
public void destroy()
{
// code
}
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance
Important Key Points about destroy() Method:
The destroy() method is called only once.
It is called at the end of the life cycle of the servlet.
This method performs various tasks such as closing connection with the database, releasing
memory allocated to the servlet, releasing resources that are allocated to the servlet and other
cleanup activities.
After destroy() method the Servlet instance becomes eligible for garbage collection.