What is Servlet in Java

What is servlet in Java? Servlets are server-side components that provide a powerful mechanism for developing server-side Java programs. It provides component-based, platform-independent methods for building web-based applications without the performance limitations of CGI programs. 

Using servlets web developers can create fast and efficient server-side applications which can run on any servlet-enabled web server. Servlets run entirely inside the Java virtual machine. Since the servlet runs on the server-side, it doesn’t check the browser compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receiving all the benefits of the mature Java language including portability, performance, reusability, and crash protection. 

Servlets are not designed for specific protocols. But they are most commonly used with HTTP protocols. Servlets provide a way of creating sophisticated server-side extensions in a server as they follow the standard framework and use the highly portable Java language.

Servlet Definition

Servlet is a Java-based server-side web technology that allows to develop its web components as single instance multiple thread-based web components.

The Servlet is a Java-based web technology that allows us to develop dynamic web components having the ability to generate dynamic web pages.

The servlet is JEE module server-side web technology that can be used to enhance the functionality of a web server or HTTP server.

Servlet is a JEE module server-side web technology that looks like rules and guidelines for vendor companies to develop Servlet containers and the same things look like API for programmers to develop server-side web components in Java web applications.

What is a Servlet component:- It is a Java class that is developed using Servlet API. Servlet container manages servlet component life cycle i.e. creating, managing, and destroying servlet class objects will be taken care by the servlet container.

Servlet in Java

The servlet is a thread-based server-side web technology it means If we give 100 requests to 1 servlet component then the servlet container will create only 1 object for that servlet component and starts 100 threads on that object representing 100 requests. This makes the servlet component a “single instance – multiple threads” component.

Advantages of Java Servlet

  1. Portability:- The servlet components are written in Java and follow well-known standardized APIs so they are highly portable across operating systems and server implementations. Servlets are WORA (write once, run anywhere) components. We can develop a servlet on a windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like the Unix server running different servers.
  2. Powerful:- Servlet components can do several things which were difficult or even impossible to do with CGI. For example, servlets can talk directly to the webserver while the CGI components can’t. Servlets can share data with each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request.
  3. Efficiency:- Servlets invocation is highly efficient compared to CGI. When the servlet gets loaded in the server, it remains in the server’s memory as a single object instance. However, with one servlet component there can be multiple threads but only one copy of the servlet class object. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable.
  4. Safety:- Servlets are written in Java, therefore they inherit a strong type of safety of Java language. Due to Java’s automatic garbage collection and lack of pointer, it is safe from memory management problems. The errors can be easily handled through exception handling mechanisms.
  5. Integration:- Servlets are tightly integrated with the server. Servlets can use the server to translate the file paths, perform logging, check authorization, and MIME types mapping and e.t.c.
  6. Extensibility:- The servlet API is designed in such a way that it can be easily extensible. Currently, Servlet API supports HTTP servlets, and later it can be extended to another type of servlets.
  7. Inexpensive:- There are a number of free web servers available for personal use or for commercial purposes. Web servers are relatively expensive, so by using the freely available web servers we can add servlet support to it.

Uses of Servlet

HTTP servlet typically used to:-

  • Provide dynamic content like getting results of a database query and returning to the client.
  • Processing and/or storing the data submitted by the HTML form.
  • Servlet can handle multiple requests concurrently and can be used to develop a high-performance system.
  • Managing state information on the top of a stateless HTTP. Example:- for an online shopping cart system that manages shopping carts for many concurrent customers and maps every request to the right customer.

Servlet API

The servlet API is given for developing server-side web components in Java web applications. Software vendor companies take as rules and guidelines to develop Servlet containers. It contains 4 packages.

Package names up to Java EE,

  • javax.servlet
  • javax.servlet.http
  • javax.servlet.annotation
  • javax.servlet.descriptor

After changing the JEE name from Java EE to Jakarta EE (see 1, 2, 3 – Feb 2018) the package name “javax” is also changed to “jakarta”.

Servlet API latest version is 5.x (5.0 version release on September 07, 2020) and its packages are,

  • jakarta.servlet
  • jakarta.servlet.http
  • jakarta.servlet.annotation
  • jakarta.servlet.descriptor

Important Resources of Servlet API

The three most important resources of Servlet API are:-

  • jakarta.servlet.Servlet (I)
  • jakarta.servlet.GenericServlet (AC)
  • jakarta.servlet.http.HttpServlet (AC)
Java Servlet API important Resources


It is an interface containing 5 public abstract methods. The methods are:-

  1. void init(ServletConfig sc) throws ServletException
  2. void destroy()
  3. void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  4. void getServletConfig()
  5. String getServletInfo()

Note:- The central abstraction in the servlet API is the Servlet interface. All servlet components implement this interface either directly or indirectly.


It is an abstract class implementing the above jakarta.servlet.Servlet(I). This class provides the implementation for 4 methods out of 5 methods of Servlet(I). It doesn’t implement the service(-,-) method and is maintained as an abstract method. Except for these 5 methods this class also contains its own direct methods.

In a Java class if at least one method is an abstract method then the class must be declared as an abstract class. Since the GenericServlet class contains one abstract method service(-,-) therefore it is declared as an abstract class. 


It is an abstract class extending from jakarta.servlet.GenericServlet (AC). It is an abstract class but doesn’t contain any abstract method.

In Java, an abstract class can contain only abstract methods or only concrete methods or both abstract and concrete methods. GenericServlet is an example of an abstract class that contains both concrete and abstract classes. HttpServlet is an example of an abstract class that contains only concrete methods i.e. no abstract method.

HttpServlet class contains 2 service(-,-) methods. One service(-,-) is an implementation of superclass GenericServlet (AC), and the other service(-,-) method is a direct method of HttpServlet class.

  • void service(ServletRequest req, ServletResponse res) throws ServletException, IOException:- implementing from super class.
  • void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException:- direct method of this class.

It also contains 7 doXxx(-,-) methods. Those doXxx(-,-) methods are:- doGet(-,-), doPost(-,-), doPut(-,-), doDelete(-,-), doOptions(-,-), doHead(-,-), and doTrace(-,-). The signature of these 7 doXxx(-,-) methods are:- protected void doXxx(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException.

The above-mentioned packages and methods are regularly used in the servlet component development process.

GenericServlet vs HttpServlet

The difference between GenericServlet and HttpServlet in tabular form,

The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.The HttpServlet is an abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol.
GenericServlet is not specific to any protocol.HttpServlet only supports HTTP and HTTPS protocol.
It doesn’t include protocol specific methods for handling the request parameters, cookies, sessions and setting response headers.The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.

Before going further, you should know:- What is a servlet container and how it works.

Why Web Component doesn’t contain main method

While servlet component development there will not be any main(-) method because it is not a standalone application to begin the execution from the main(-) method. We develop the main(-) method if it is a standalone application where JVM directly executes the application. But it is a web component whose life cycle is managed by a Servlet container. The servlet container is calling the life cycle methods to manage the life cycle of servlet components. We will work with those life cycle methods. Therefore we never develop the main(-) method while developing web applications.

The servlet container calls service(-,-) method as a life cycle method on the servlet component for every request. So, we place request processing logic in the service(-,-) method of the servlet component.

We are not going to execute the servlet component through command prompt, it will be executed by a servlet container that calls service(-,-) method as part of the life cycle method.

Note:- Servlet Container takes only those Java classes as servlet components who are implementing Servlet(I) directly or indirectly.

Approach to Develop Servlet Component

There are three approaches to develop servlet components. 

Approach1:- Through Servlet(I). Take a Java class implementing jakarta.servlet.Servlet(I), provide the implementation for all the 5 methods, keep the request processing logic in service(-,-) method. 

Limitation of this approach,

  1. Generally, we need to place only request processing logic in the service(-,-) method but in this approach, we are forced to implement all 5 methods of Servlet(I) even though the remaining 4 methods are not required.
  2. We can’t work with protocol HTTP features like auto-refresh feature and e.t.c.

Due to these limitations, it is not a recommended approach, and therefore it is not a standard approach.

Approach2:- Through GenericServlet(AC). Take a Java class extending jakarta.servlet.GenericServlet(AC) and provide implementation only for service(-,-) method having request processing logic. Override the other 4 methods only if it is required.

Advantages:- We need to implement only the service(-,-) method and override the other method only if required. It doesn’t force us to implement other methods.

Disadvantage:- Here also we can’t work with protocol HTTP features like auto-refresh feature and e.t.c. Therefore it is also not a recommended approach and not a standard approach.

Approach3:- Through HttpServlet(AC). Take a Java class extending from jakarta.servlet.http.HttpServlet(AC) and override one of two service(-,-) methods or one of 7 doXxx(-,-) methods having request processing logic. 

The Servlet(I) and GenericServlet(AC) don’t allow us to use protocol HTTP features, only HttpServlet(AC) allows us to use protocol HTTP features.

The limitations of approach-1 and approach-2 are solved in this approach, and we can work with protocol HTTP features therefore it is a recommended approach and standard approach.

Note:- We must take our servlet component class as a public class to make it visible outside its packages. So that the servlet containers can load the class and can manage the life cycle.

Java Web Application Deployment Directory Structure

   |=> WEB-INF
      |=> web.xml
      |=> lib
      |=> classes
   |=> HTML files
   |=> Static Resources (image, audio, video, css, e.t.c.)
Web application deployment directory structure

The above directory structure represents the web application that is deployable in the server, so it is called the deployment directory structure. This directory structure is common for all Java servers. It is designed by Sun Microsystems and followed by all vendor companies that create web server software. In the above deployment directory structure, some names and their locations are fixed including the cases (case-sensitive):- “WEB-INF”, “lib”, “classes”, and “web.xml”. The web servers are designed like this so that we must use those fixed names at their positions.

  • Here “WebApplication” is the root folder name and this name is the developer’s choice. Later this name became the name of the web application.
  • WEB-INF folder is acting as a logical partition between private and public areas of the web applications. Outside of the WEB-INF folder is called the public area, and inside of the WEB-INF folder is called the private area. The name “WEB-INF” is fixed (all characters in uppercase).
  • The “lib”  folder will contain the resources file like the JDBC driver jar file. The “lib” name is fixed, and all characters must be in the lowercase.
  • The “classes” folder contains the web components and Java classes. The “classes” name is also fixed, and all characters must in lowercase.
  • web.xml” file contains various configurations like Servlet component configuration, home page configuration, and e.t.c. This filename is also fixed.

Providing details about certain files or web components to make the underlying server or container recognize that file or component as a special component is called configuration of file or component. Such configuration in web applications can be done by using a web.xml file. So, the web.xml file is called a web application configuration file which contains Servlet configuration, JSP configuration, and e.t.c.

In the deployment directory structure of the Java web application, only 4 standard names are there. They are:- a)WEB-INF, b)classes, c)web.xml, d)lib, and all these belong to the private area of the web application. The remaining all folder and file names are developer choice names.

Public and Private Area of Deployment Directory Structure

The public and private area of the deployment directory structure is separated by the WEB-INF folder. Outside of the WEB-INF folder is called a public area, and inside of the WEB-INF folder is called a private area.

Private area of the web application:- only underlying server/container can use this area directly. The folders and files in the private area are- web.xml file, lib folder, and classes folder.

The public area of the web application:- Anyone can access this area without web server permission. The HTML/JSP files and all static resources files are placed in the public area.

Requests coming to public area web components like HTML files don’t need any web server/container permission to execute the web component whereas the request coming to private area web components will execute only with permission of the webserver/container and we need to get permission through web.xml file entries.

Java classes and Java classes web components are asked to place in a private area to provide protection for source code (.java) and byte code (.class). We place static web components in the public area because they go to the browser for execution. So, there is no possibility of protecting the source code of these files whereas the Java servlet components execute in the web server itself and don’t go to the browser. Therefore, source protection is possible for servlet components by keeping them in a private area.

Note:- The web container generally looks for Java classes & Servlet components in private areas and it looks for static web components (HTML/JSP files) and helper web components (like image, audio, video, and e.t.c.) in the public area of the web application.

Java Servlet Request and Response Object

For every request that comes through the browser, the servlet container creates 1 set of request, and response objects and also calls the service(-,-) method on the servlet component having that request, response object as the arguments.

The programmer uses those request, response objects in the service(-,-) method while writing the request processing logic. The request object is very useful to gather inputs that are coming along with the request (like form-data), whereas programmers place generated output in response objects in order to send it to the browser as a response.

The output/results written to response objects go to the browser through a web container and web server. Finally, browsers display that output or response as a web page. The order is:- service(-,-) generates output => output goes to response object => response came back to web container => web container hand-over it to web server => web server send it to the browser => browser receive it and display result as web page.

The response object is having one built-in stream called PrintWriter. The destination (where output will be written) for the PrintWriter is the response object itself. By calling response.getWriter() method we get that stream and we use it to write output to the response object by calling println() method of PrintWriter class.

// service(-,-) method (declared in Servlet(I)
public void service(Request req, Response res) 
              throws ServletException, IOException {
   // to get PrintWriter stream
   PrintWriter pw = res.getWriter();

   // to write output to PrintWriter
   pw.println("<h1>Welcome to Servlet</h1>");

   // close stream

As System.out stream is pointing to console/monitor so System.out.println(-) method writes the message to console/monitor. Similarly, res.getWriter() gives PrintWriter stream pointing to the Response object itself therefore pw.println(-) writes the messages to the response object.

Why do most of the servlet methods throw IOException and ServletException?

  • We use PrintWriter or other streams in the service(-,-) method to write the generated output message to the response object. In this process, there is a possibility of getting an IOException. 
  • If the web container is having any problem with calling and executing the service(-,-) method then it throws ServletException.

How web.xml file is used

Servlet technology is giving rules to construct web.xml files having fixed tag names and attribute names in the form of DTD ( Document type definition) or XSD (XML schema definition). 

If an XML document is satisfying basic syntax rules (strictly typed rules) then it is called a “well-formed XML document”. Strictly typed rules/basic syntax rules,

  • Tag, attribute names are case-sensitive.
  • The tag must be nested properly.
  • Special characters are not allowed in tag, attribute names.
  • Attribute values must be quoted (either with single or double quote)
  • and e.t.c.

If an XML document satisfies DTD/XSD rules then it is called a valid XML document. An XML parser is a Java-based software program that can perform the following operations,

  1. Loading XML document.
  2. Checking well-formed, valid or not?
  3. Reading XML file content.
  4. Create InMemory metadata of XML file content.
  5. Processing XML file content and e.t.c.

Example of XML parsers are:- SAX parser (Simple API for XML Processing), DOM parser (Document Object Model), JDOM parser (Java Document Object Model), DOM4J parser (Document Object model for Java), and e.t.c.

We can see these DTD/XSD for web.xml file in the servlet-api.jar file (Inside jakarta.servlet.resources folder).

Servlet container uses an XML parser to create InMemory metadata of web.xml file by loading and verifying web.xml file. The InMemory will be created where the application runs (i.e. in JVM memory of RAM) and that metadata will be used multiple times during the execution of the application. This improves the performance because it avoids loading XML files multiple times, verifying XML files multiple times.

The moment a web application is stopped its JVM memory in the RAM will vanish. In that process, InMemory metadata of XML files like web.xml will also vanish. 

For one web application, XML files will be loaded, verified, metadata created only for one time at the time of deployment. That metadata will be used for all the requests. The modification done in the content of the web.xml file will reflect itself through the web container, no need to reload the web application to get the updated content.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.