🧾 Chapter 1: Introduction to Servlets – The Foundation of Java Web Development

Table of contents
- Part of: The Full Stack Java Development Series
- Introduction
- 1. Types of Applications Built Using Java
- 2. Understanding the Role of JVM and Server Software
- 3. What Is a Web Application?
- 4. What Is a Distributed Application?
- Web Application and Distributed Application Architecture
- Difference Between Web Application and Distributed Application
- Real-World Scenario: The BookMyShow Use Case
- Key Concepts and Terminology
- Conclusion
- Section 5: Client-Server Architecture – The Backbone
- 🔹 What Is Client-Server Architecture?
- 🔹 Why Software Talks to Software, Not Hardware to Hardware
- 🔹 Understanding the Role of the Client
- 🔹 Understanding the Role of the Server
- 🔹 End-to-End Interaction Flow
- 🔹 Importance in Servlet-Based Applications
- 🔹 Interview-Focused Summary Points
- 🔹 Real-World Analogy – Restaurant Model
- 🔹 Final Notes
- 6. Static vs. Dynamic Responses in Web Programming
- 🧩 Static Response – A Lightweight Interaction
- 🧩 Dynamic Response – Personalized, Context-Sensitive Output
- 🧱 Role of the Web Container
- 🔧 Execution of Helper Application – The Detailed Lifecycle
- 💡 Key Technologies Used for Dynamic Responses
- 📌 Note for Developers
- 🧠 Comparison Summary: Static vs Dynamic Response
- ✅ Final Thoughts
- 7. What Is a Web Server?
- 8. Introduction to Servlet
- 9. Servlet Container and Server Vendors
- 10. How a Servlet Works Internally
- 11. CGI vs. Servlet – Why Servlet Is Better
- 🚀 Servlet Architecture and Java Threading (In-depth Theory)
- 1. Servlet as a Java-Based Web Technology
- 2. Java’s Thread-Based Nature
- 3. Internal Servlet Architecture: Execution Flow (Conceptual Flow Explanation)
- 4. Why Threads Are Better Than Processes
- 5. Thread Pool in Servlet Container
- 6. ServletContext and Thread Interaction
- 7. Summary: Servlet’s Scalable Multithreaded Model
- Key Takeaway (Interview Perspective)
- Chapter 12: Servlet vs. JSP – Understanding Their Role in Java Web Applications
- Chapter 13: MVC Architecture in Java Web Applications
- MVC Request-Response Flow – Explained Step by Step
- Optional Flow: View Accessing the Model
- Summary of MVC Responsibilities and Technologies
- Conclusion: Why MVC Matters in Java Web Development
- 14. Tomcat Server Architecture – A Complete Theory Explanation
- 1. Tomcat Server – The Entire Software Environment
- 2. Web Server Layer – First Interface to Clients
- 3. Web Container – The Runtime for Dynamic Java Content
- 4. Servlet Container or Servlet Engine (CATALINA)
- 5. JSP Container or JSP Engine (JASPER)
- 6. Combined Architecture: How Components Work Together
- Why This Separation Matters – Real World Understanding
- Supporting Components (as per your notes)
- Conclusion
- 14.2 Structure of Deployed Application in Tomcat
- 15. Developing a Web Application Using Servlet
- 16. Summary of Servlet API Packages
- ✅ Final Thoughts

Part of: The Full Stack Java Development Series
Introduction
In the realm of software development, especially in Java, web development has its own landscape. When developers say they’re building web applications using Java, it often begins with a technology called Servlet. But before diving into Servlet, let’s understand the full picture—what kinds of applications Java allows us to build, why servers are essential, what a web application really means, and how requests and responses work in the client-server architecture.
1. Types of Applications Built Using Java
Java is a versatile and powerful language. Depending on the purpose of the software, Java allows us to build three major types of applications:
a) Standalone Applications (Java SE - Standard Edition)
These are traditional desktop-based applications. They can be further classified into:
CUI (Console User Interface) Applications: Text-based programs, often used for learning purposes or internal tools.
GUI (Graphical User Interface) Applications: These are interactive programs with window-based interfaces like Swing or JavaFX.
b) Enterprise Applications (Java EE - Enterprise Edition)
These applications are large-scale, server-side applications, often used in business and enterprise environments. They are further divided into:
Web Applications: Client-server models accessed via browsers.
Distributed Applications: Applications that distribute their logic across multiple servers or JVMs.
c) Mobile Applications (Java ME - Micro Edition)
This edition was once used for mobile app development, but it is now deprecated. Today, mobile apps are typically built using modern platforms like Android, React Native, or Flutter.
2. Understanding the Role of JVM and Server Software
Let’s begin by stepping back and understanding something very fundamental: how Java applications execute and what infrastructure they need.
Every Java program, whether a simple command-line tool or a full-fledged enterprise web application, needs one thing to run—the Java Virtual Machine, or JVM. The JVM is like the heart of the Java platform. It is responsible for taking the compiled .class
files (which are nothing but Java bytecode) and executing them on the machine, regardless of the underlying operating system.
Now, when we move from basic Java applications to web-based applications, the environment changes. In the case of web development, Java applications are not just meant to run locally. They are expected to serve users across the internet, over a network. That’s when a new concept is introduced—server software.
Server software is a specialized program installed on a computer (referred to as a server) that provides an environment for hosting and running web applications. Inside this environment, developers deploy their applications so they can handle user requests from anywhere across the world.
Let’s imagine you have written a Java program that needs to respond to user input sent through a browser. That program alone isn’t enough. You will have to deploy it inside an ecosystem where:
Requests are accepted from clients (browsers).
The Java program is properly managed and executed.
The appropriate response is returned back to the client.
This is exactly what server software provides.
Even if your web application contains just one Java class, it cannot run without a JVM. And to make it accessible over a network like the internet, the system must have both the JVM and the server software. Without these, your application will not be reachable to end-users sitting miles away, sending requests through browsers.
In summary, if Java code is the brain, the JVM is the nervous system that executes it, and the server software is the body in which the application lives and interacts with the outside world. These three together form the core setup for any Java-based web solution.
3. What Is a Web Application?
Now that we have a clear picture of the execution environment, let’s understand what we are building within it.
A web application is a type of application that lives on a server and is accessed by users through a web browser. It is designed to receive HTTP requests from clients (like browsers or mobile apps) and send back HTTP responses that the browser can render. These responses are often dynamic, meaning they vary based on the user, the time, or the nature of the request.
The defining characteristic of a web application is that it is browser-facing. That means users need only a browser and an internet connection to interact with the application. They type a URL or click a link, and the browser sends a request to a server where the web application is deployed.
At the backend, the Java web application is running inside a single JVM. All the application logic—business rules, data access logic, presentation logic—is confined within this single environment. The server receives the request, the Java program processes it, and the result is sent back as a response—typically as HTML, CSS, or JavaScript, which the browser can interpret.
Let’s take a real-world example.
When you open a website like BookMyShow, and you see a list of upcoming movies in your city, that’s a classic case of a web application. The application logic—filtering movies based on location, timing, availability—is all running on one server. The client (browser) merely sends the request and waits for the result.
Common technologies used in web applications include:
Frontend: HTML, CSS, JavaScript
Backend: Servlet, JSP, CGI
Server: Web servers like Apache Tomcat
In terms of architecture, web applications are simple and effective, built to handle browser-based requests efficiently. They are perfect for most standard use cases like online portals, login systems, blogs, dashboards, and many more.
4. What Is a Distributed Application?
While web applications are sufficient for many scenarios, they start to fall short when complexity grows—especially in large-scale systems that integrate with third-party services, external APIs, or need to handle massive load.
That’s where distributed applications come in.
A distributed application is one in which the application logic is not restricted to a single JVM or a single machine. Instead, it is spread across multiple machines, each running its own instance of the JVM. These machines may be on the same network or located in different parts of the world. The idea is that different parts of the application can live and run independently, and still work together to complete a single request.
The key difference lies in the architectural design. In a web application, everything happens inside one JVM. But in a distributed application, the client might interact with one server, and that server might forward the request to another server for further processing. This second server could be a remote system entirely—perhaps responsible for payment processing, file storage, authentication, or analytics.
To enable this, distributed applications rely on technologies that allow machine-to-machine communication, such as:
RMI (Remote Method Invocation): Allows calling methods on an object located in another JVM.
EJB (Enterprise JavaBeans): Provides a framework for building scalable, transactional business components.
Web Services (SOAP or REST APIs): Enable communication using standardized HTTP protocols.
Let’s return to our BookMyShow example.
When a user selects a showtime and clicks “Proceed to Pay,” the web application must now involve a third-party payment gateway like Razorpay, PayU, or a bank’s payment service. BookMyShow doesn’t process payments internally. It simply forwards the necessary details to the external service. This external service is running on another server, managed by a different company, and has its own JVM and business logic. Once the payment is processed, the response is sent back to BookMyShow.
This model of working—where different systems are responsible for different parts of the logic, and yet they coordinate through a network—is the essence of a distributed application.
Web Application and Distributed Application Architecture
When designing either a web or a distributed application in Java, a few things remain constant:
Server Software is essential.
Java Code must be executed inside a JVM.
Clients send requests using the network.
Servers receive, process, and respond.
The difference is in where and how many servers and JVMs are involved.
Web Application Architecture
Java code is deployed inside one server software (like Tomcat).
The application is accessed via browser.
All logic executes in a single JVM.
Technologies used: Servlet, JSP, HTML, JavaScript.
The server directly communicates with the browser.
It’s a Client-to-Server model.
Distributed Application Architecture
Multiple server instances, each with its own JVM.
Different modules may live on different machines.
Communication happens between machines (servers).
Technologies used: RMI, EJB, RESTful services.
It’s a Business-to-Business (B2B) model.
Difference Between Web Application and Distributed Application
Criteria | Web Application | Distributed Application |
Definition | Single JVM, logic confined to one server | Logic split across multiple JVMs and machines |
Communication Model | Client to Server | Server to Server (B2B) |
Client Type | Browser, mobile app (HTTP-based) | Any client (web, mobile, backend system, remote service) |
Technology Used | Servlet, JSP, HTML, CSS | RMI, EJB, SOAP/REST APIs |
Purpose | Generate and serve dynamic content from one location | Allow remote access, external service integration, or distributed computation |
Server Type | Web Server (Tomcat, Jetty) | Application Server (JBoss, WebLogic, GlassFish) |
Example | Movie listing page in BookMyShow | Payment gateway integration in BookMyShow |
Real-World Scenario: The BookMyShow Use Case
Let’s visualize how a real-world application transitions from a web application to a distributed application during its lifecycle.
A user opens the BookMyShow website and selects a movie in their city.
The web application running on a single server (one JVM) receives the request and fetches movie details from a local database.
The available shows are displayed. So far, everything is handled within a single machine—this is a web application.
Now the user proceeds to payment. BookMyShow forwards the transaction details to PayU, a third-party payment gateway.
This gateway is not part of BookMyShow’s server. It’s a remote application hosted on another machine with its own JVM.
After the payment is processed, the response (success or failure) is returned to BookMyShow.
This second part of the flow—where BookMyShow interacts with PayU—is a classic example of a distributed application.
Key Concepts and Terminology
Client: A software program that sends a request to a server. It could be a browser, mobile app, or another server.
Server: A program or machine that listens to requests, processes them, and sends back appropriate responses.
Web Server: A server software that processes HTTP requests for static and dynamic resources. Examples include Tomcat, Jetty.
Application Server: A server with extended capabilities like transaction management, remote method invocation, and enterprise integration. Examples include JBoss, WebLogic.
Conclusion
In summary, understanding the role of JVM, the function of server software, and the architecture of web and distributed applications is critical for any aspiring Java backend or enterprise developer.
A web application handles user requests through a browser using a single JVM and is ideal for simpler workflows.
A distributed application handles complex workflows across multiple systems and JVMs, enabling remote services and third-party integration.
This clear distinction helps developers make better design decisions and prepare more effectively for interviews and real-world project work.
Section 5: Client-Server Architecture – The Backbone
Before diving into how Servlets work, it is absolutely essential to understand the architecture that forms the foundation of all web-based applications—Client-Server Architecture. This model is not specific to Java or Servlets; it is a universal concept used in web development, networking, enterprise systems, and beyond.
🔹 What Is Client-Server Architecture?
Client-Server Architecture is a distributed application structure that separates tasks or workloads between two entities:
Client: the machine (or software) that initiates the communication by making a request.
Server: the machine (or software) that listens for requests, processes them, and returns an appropriate response.
This is fundamentally a two-tier architecture, and it’s designed to work over a network—whether it be a local network (LAN) or the Internet.
This architecture is request-driven, which means nothing happens unless the client sends a request. In other words, all the power to begin communication lies with the client.
🔹 Why Software Talks to Software, Not Hardware to Hardware
While we often refer to “client” and “server” as physical machines, it is not the hardware that actually initiates or processes communication. In reality, the interaction is purely software-based:
On the client machine, a piece of software like a browser (Chrome, Firefox, Edge) sends a request to the server.
On the server machine, a specialized server software like Apache Tomcat or JBoss receives this request, processes it through the deployed web application, and sends back the response.
In short, software communicates with software over the network. Hardware merely acts as a medium to host and run that software.
🔹 Understanding the Role of the Client
The client is any system (or program) that sends a request to the server. Most commonly, this is a web browser installed on a user’s computer or mobile device. When the user enters a URL like http://localhost:8080/StudentApp
, the browser sends an HTTP request over the network to the server.
The browser doesn’t just send the request—it also waits for the response, and upon receiving it, renders it visually for the user.
From a technical standpoint, the browser:
Initiates the request
Encodes the request in a network-compatible format (usually HTTP or HTTPS)
Sends it to a specific server IP and port
Parses and displays the response
Thus, the browser acts as a client-side software interface through which users interact with remote server applications.
🔹 Understanding the Role of the Server
The server in this context is a software program running on another machine. Its job is to:
Listen for incoming client requests.
Identify the resource or application logic to handle the request.
Execute the logic, possibly by calling Java code, querying a database, or interacting with another system.
Generate and return an appropriate response (HTML, JSON, etc.).
This server software must support HTTP-based communication (which is why we need web servers like Apache Tomcat, Jetty, or GlassFish).
Moreover, the web server contains a web container or servlet container that specifically handles Servlet and JSP components. It is within this container that the actual Java-based server logic executes.
🔹 End-to-End Interaction Flow
Here’s a theoretical breakdown of how this communication typically works:
The user interacts with a browser and initiates a request by visiting a URL or submitting a form.
The browser packages this request into an HTTP format and sends it to the specified server address over the network.
The web server software receives the request.
The server identifies whether the request is for a static resource (like an HTML page) or a dynamic resource (like a Servlet).
If dynamic, the request is handed over to the web container, which locates the corresponding helper application (Servlet or JSP).
The Java logic within the Servlet is executed, and a response is generated.
The server sends this response back to the browser.
The browser displays the response to the user.
This is a one-cycle interaction, and each new request initiates a new cycle. The client and server are said to be loosely coupled, meaning they only interact during the lifecycle of a request-response pair.
🔹 Importance in Servlet-Based Applications
This entire architecture is the execution ground for Servlet technology. Servlets are not standalone programs; they are meant to live and function inside a server. Without a client to initiate requests and a server to host the servlet, the servlet has no value.
The client sends a request via browser (HTTP GET or POST).
The server delegates to the servlet container.
The Servlet executes logic and generates dynamic output.
The response is returned to the client.
This is the foundation of every Java web application, making the understanding of client-server architecture absolutely critical before progressing with Servlet development.
🔹 Interview-Focused Summary Points
If you're in an interview and asked to explain client-server architecture in the context of Java web development, you should emphasize:
A client is any software (usually a browser) that initiates a request to access a resource or service.
A server is a specialized software running on a machine that listens for incoming requests and returns appropriate responses.
The interaction is request-response based and occurs over a network.
Communication happens between software components, not hardware devices.
A web application must be deployed inside server software (like Tomcat) for it to be accessed.
The Servlet container inside the server handles the dynamic logic of Servlets and JSPs.
All interaction is initiated by the client, making the architecture client-driven.
The browser uses protocols like HTTP/HTTPS to send and receive data.
Every time a user sends a new request, a new lifecycle begins. These cycles are stateless by default unless session tracking is explicitly implemented.
🔹 Real-World Analogy – Restaurant Model
To make this concept even easier to understand, imagine the following scenario:
The client is like a customer entering a restaurant.
The browser is the waiter that takes the order.
The server is the kitchen, where meals (responses) are prepared.
The application is the recipe book or chef's instructions.
The web server ensures that orders are managed and delivered in the right way.
Just like the customer cannot get food unless they place an order, a client does not receive any data until it sends a request. And just like the kitchen does not randomly send food unless someone asks, the server does not respond unless requested.
🔹 Final Notes
The Client-Server Architecture is the invisible backbone of all web technologies, including Servlets, JSP, Spring MVC, and REST APIs. Regardless of the technology stack, the principles remain the same:
Initiation of communication by the client
Centralized logic on the server
Stateless interaction using standard protocols
Execution of dynamic logic inside a dedicated server container
Understanding this model ensures a solid base for designing, building, deploying, and explaining Java web applications.
6. Static vs. Dynamic Responses in Web Programming
In web programming, every interaction between a user and a web application begins with a request and ends with a response. These responses can be broadly categorized into two types: static responses and dynamic responses. Understanding this distinction is crucial for Java developers, especially when working with Servlets, JSP, or any modern server-side technologies.
Let’s explore both these types in depth, starting with the simpler one.
🧩 Static Response – A Lightweight Interaction
When we talk about static response, we refer to a type of response that is fixed, unchanging, and independent of the user or the time of access. In simpler terms:
“The response which won’t be changed from person to person and time to time, such type of response is called as static response.”
This type of response is ideal for content that remains the same across all users, such as general information pages or publicly accessible resources.
🔍 Real-World Examples
Login Page of Gmail: The layout, logo, text fields, and submit button remain the same for every visitor.
Home Page of ICICI Bank: The homepage structure is identical for all users before they log in.
⚙️ How Static Response Works – A Step-by-Step Flow
The architecture involves two components:
Client machine: The user’s system where a browser (special software) is installed.
Server machine: A system where the server software is installed, containing the static files (e.g.,
.html
,.css
,.js
, images).
Here’s how the process flows:
The client sends a request to the server for a static file (for example,
index.html
).The server software searches its file system to locate the requested static resource.
If the file is found, the server copies the content of the file and sends it back as a response to the client browser.
If the requested file is not found, the server returns a 404 Not Found status code with a message indicating “requested resource not available.”
🧠 Important Interview Insight
“To serve static files, no processing is required at the server side, hence webserver always loves to serve static files.”
This is a crucial point. Since static files do not require any computation, logic processing, or database access, they are fast and lightweight. This is also why web servers prefer serving static content over dynamic ones — it consumes less memory, involves no Java logic, and improves server response time.
In short, a static response is the easiest and quickest form of interaction between client and server. It does not require a web container, JVM execution, or any helper application.
🧩 Dynamic Response – Personalized, Context-Sensitive Output
On the other side of the web development spectrum lies dynamic response, which is at the heart of most real-world applications today.
“The response which is varied from person to person and time to time, such type of response is called as dynamic response.”
This means the content sent as a response by the server depends on:
The identity of the user (e.g., user account info)
The specific data requested (e.g., search result)
The time of the request (e.g., current news, account balance)
🔍 Real-World Examples
Inbox page of Gmail: Your inbox content is different from someone else's.
Balance page of ICICI Bank: The balance shown is based on the account holder and changes over time.
⚙️ How Dynamic Response Works – Step-by-Step Flow
The architecture is more sophisticated in this case. Here's how the request and response mechanism for dynamic web programming works:
The client (browser) sends a request to the web server.
The web server checks whether the request is for a static resource (like
.html
) or a dynamic resource (like.jsp
or a servlet-mapped URL).If the request is for a static file, the server searches and returns it directly (as discussed in the static response flow).
If the request is for a dynamic resource, the web server hands over control to the web container.
🧱 Role of the Web Container
A web container is a specialized component inside the web server, designed to manage the execution of Java-based helper applications, such as:
Servlets
JSP
ASP
PHP
CGI
This web container internally uses the Java Virtual Machine (JVM) to run Java logic.
🔧 Execution of Helper Application – The Detailed Lifecycle
The web container now searches for the helper application (a
.java
or.class
file, typically a servlet) that matches the request.If the helper application is not found, the container sends a 404 status code back to the client saying “requested resource not available.”
If the helper application is found, it is executed using the JVM inside the web container.
The response generated by the helper application is passed back to the web server.
The web server then forwards that response to the client.
⚠️ Error Handling in Dynamic Response
During this process, if the helper application throws any exception or encounters an error during execution, then the server sends a:
500 Internal Server Error – indicating an error occurred while processing the dynamic content.
This response alerts the client that something failed on the server-side logic, not due to a missing file (which would have been 404).
💡 Key Technologies Used for Dynamic Responses
The technologies that support dynamic web programming are:
Servlet – Java-based backend logic for dynamic request processing
JSP (Java Server Pages) – Dynamic HTML generation using Java-based tags and expressions
ASP, PHP, CGI – Non-Java technologies, also used in other ecosystems
Each of these technologies is responsible for building helper applications that can generate dynamic, personalized, real-time responses based on user inputs and server-side logic.
📌 Note for Developers
“To generate the dynamic response at the server side, we need some helper applications. To build these applications which are capable of generating dynamic response, we need to learn technologies like Servlet and JSP.”
This is a key takeaway. If you're preparing for interviews or building web applications using Java, knowing how to write and deploy servlets or JSPs is mandatory.
🧠 Comparison Summary: Static vs Dynamic Response
Feature | Static Response | Dynamic Response |
Content | Same for every user | Varies by user and time |
Server Processing | None | Required (via web container) |
Technologies | HTML, CSS | Servlet, JSP, PHP, CGI |
Performance | Fast, lightweight | Depends on business logic complexity |
Examples | Gmail login page | Gmail inbox, account dashboard |
Error Codes | 404 (resource not found) | 500 (server-side error) |
✅ Final Thoughts
Understanding the distinction between static and dynamic responses is foundational for web developers. While static content delivers consistent pages with minimal effort, modern web development heavily relies on dynamic responses to deliver personalized, interactive, and real-time experiences.
From the Gmail inbox that updates with your latest messages to a ticket booking system that checks live seat availability — all of these use dynamic programming techniques, powered by technologies like Servlets and JSP.
As you progress in your Java web development journey, this concept will recur in nearly every project and interview. Be sure you not only understand it theoretically but also know how to implement it using Java-based tools.
7. What Is a Web Server?
A web server is a software that:
Accepts browser requests (HTTP).
Handles static resources directly.
Delegates dynamic resource handling to web containers.
Examples:
Tomcat
Jetty
Resin
JBoss
GlassFish
Deployment refers to copying your web application into this server environment. Removal is called un-deployment.
8. Introduction to Servlet
A Servlet is a Java program that runs on the server and responds to HTTP requests. It is the backbone of Java-based web development.
Servlet is part of the Servlet API, and it offers a set of interfaces and classes defined under:
javax.servlet.*
javax.servlet.http.*
However, Sun Microsystems (Oracle) only provides interface definitions, and expects server vendors to implement them.
9. Servlet Container and Server Vendors
In any Java web development journey, the Servlet container plays a foundational role. Also known as the Web container, it is the part of the web server responsible for executing servlets and managing their lifecycle. But a container alone is not enough—we need to understand how it interacts with the Servlet API and server vendors. The Servlet API defines only the interfaces (like HttpServlet
, ServletRequest
, etc.), while vendors like Tomcat, JBoss, and WebLogic provide the actual implementation of those interfaces. Because of this separation, as developers, we should never code using vendor-specific classes. Instead, we must code using the standard Servlet API only. This approach supports the principle of WODA (Write Once, Deploy Anywhere)—a philosophy that allows you to build one web application and deploy it on any compliant server without changing a single line of code.
10. How a Servlet Works Internally
When you build a servlet:
You either implement
Servlet
interface,or extend
GenericServlet
,or extend
HttpServlet
.
When a client sends a request to a server (like Tomcat), the server determines whether the request is for a static resource (like an HTML file) or a dynamic resource (like a servlet). If it’s a dynamic request, it is forwarded to the Servlet container. The container then fetches an available thread from the thread pool and assigns it to handle that request. This is crucial for scalability—unlike CGI, which spawns a new process per request, Servlet containers use threads, leading to better performance. The servlet code is then executed inside the JVM, and once the logic completes, a response is sent back to the client. This request-response handling using lightweight multithreading is a key performance advantage of servlets.
11. CGI vs. Servlet – Why Servlet Is Better
In early web development, the first approach used to generate dynamic web content was CGI, or Common Gateway Interface. But today, CGI is rarely used in modern Java web applications. This raises a common interview question:
“If CGI already existed to handle dynamic server-side responses, then why was Servlet introduced?”
Let us understand the answer in a structured and conceptual way.
CGI (Common Gateway Interface): An Outdated Approach
CGI is a technology that was designed to generate dynamic content on the web. It was written in the C programming language, and relied on the operating system to create a separate process for each incoming client request.
Whenever a client (e.g., browser) sent an HTTP request, the web server (like Apache HTTPD) would:
Create a new OS-level process.
Pass the client request to this newly spawned process.
Execute the CGI script.
Generate a dynamic response.
Return it to the client.
This model, while functional for small-scale systems, suffers from major drawbacks.
Problems with CGI (Process-Based Model)
One Process per Request: For every request, a new process is created by the operating system. This consumes more memory and CPU resources.
Heavyweight Execution: OS processes are heavyweight. Creating and destroying them is expensive in terms of time and system overhead.
Low Scalability: If 100 clients send 100 simultaneous requests, 100 processes are created. As the number of users grows, system performance drops drastically.
Longer Response Time: Every request incurs the overhead of process creation, leading to delays.
Higher Memory Usage: Each process has its own memory allocation and cannot share memory with others, leading to poor memory efficiency.
In simple terms: More users = More processes = More load = Slower system
Let’s consider a real-world use case like BookMyShow. Imagine thousands of users booking tickets simultaneously. If CGI were used here, the server would crash under the load because it would create thousands of processes at once.
Servlet: A Thread-Based, Scalable Alternative
To overcome the inefficiencies of CGI, Java introduced Servlets. Servlet is a Java-based web technology that uses multi-threading instead of process-based execution.
In the Servlet model:
Only one object of the servlet class is created (a singleton).
For each client request, a new thread is created (or reused from a thread pool) instead of a new process.
These threads are lightweight and run inside the same JVM, managed by the Servlet container (like Tomcat).
This approach improves performance, resource utilization, and scalability significantly.
Benefits of Servlet (Thread-Based Model)
Single Object, Multiple Requests: The Servlet container creates one servlet object and uses it to serve all incoming requests.
Multi-threaded Request Handling: Each request is handled in a separate thread, allowing concurrent processing.
Thread Pool Usage: Most servers (like Tomcat) maintain a thread pool, which helps in reusing threads without creating new ones every time.
Low Memory Overhead: Threads share the same memory space. This improves memory efficiency and avoids excessive garbage collection.
Minimal Context Switching: Since all threads operate inside the same JVM process, switching between threads is fast and efficient.
High Scalability: Even thousands of requests can be handled simultaneously with proper thread management.
No OS-Level Involvement: The entire thread model is managed by the Java Virtual Machine, reducing reliance on the operating system.
Conclusion: Why Servlet Is Preferred Over CGI
Aspect | CGI | Servlet |
Language | C | Java |
Execution Model | One process per request | One thread per request |
Overhead | High (process creation) | Low (thread reuse) |
Memory Consumption | High | Low |
Scalability | Poor | High |
Performance | Degrades with more users | Remains stable under load |
OS Involvement | High | Minimal (handled by JVM) |
In interviews, the key takeaway is:
CGI is a process-based model that consumes heavy resources and cannot scale. Servlet is a thread-based model that ensures high performance, efficiency, and scalability.
🚀 Servlet Architecture and Java Threading (In-depth Theory)
Understanding why Servlet is efficient requires looking at its internal multithreaded architecture.
1. Servlet as a Java-Based Web Technology
Servlet is a server-side technology written in Java. Since Java is inherently multithreaded, Servlet technology leverages Java’s built-in concurrency to handle requests efficiently.
2. Java’s Thread-Based Nature
In Java:
Threads are lightweight units of execution.
Multiple threads can run within the same process and share memory.
Thread creation and management are handled by the JVM, not the OS.
This makes Java ideal for building scalable, concurrent web applications.
3. Internal Servlet Architecture: Execution Flow (Conceptual Flow Explanation)
Let’s break this into clear steps:
a. Request Reception
Multiple clients (Client-1, Client-2, ..., Client-n) send HTTP requests to the server.
b. Request Identification
The web server receives the request and checks whether it's for a static or dynamic resource.
If static: HTML/CSS files are served directly.
If dynamic: The request is forwarded to the Servlet container.
c. Servlet Object
The Servlet container ensures that only one object of the servlet is created.
This object is stored in memory and reused across requests.
d. Thread Allocation
For each client request, a new thread is picked from a thread pool maintained by the container.
The thread executes the servlet’s
service()
method (ordoGet()
,doPost()
, etc.).After processing, the thread is returned to the thread pool.
e. Shared Resources
One object (Servlet)
One context (
ServletContext
)Multiple threads handle requests using shared read-only configurations
4. Why Threads Are Better Than Processes
Feature | Processes (CGI) | Threads (Servlet) |
Creation Time | High | Low |
Memory Usage | Separate memory | Shared memory |
Speed | Slower | Faster |
Communication | Complex (IPC) | Easy (Shared data) |
Resource Sharing | Difficult | Simple |
Scalability | Limited | Excellent |
Threads operate in the same address space, reducing context switching and enabling faster communication.
5. Thread Pool in Servlet Container
The Servlet container maintains a predefined pool of threads.
This avoids creating/destroying threads repeatedly.
Threads are reused, improving performance and reducing memory churn.
For example, Tomcat has a default thread pool size. As requests arrive, threads are picked and returned after use.
6. ServletContext and Thread Interaction
ServletContext is a shared object created during servlet deployment.
It holds application-wide configurations.
Threads can access it but should not modify shared data to avoid race conditions.
Each thread processes the client request independently, but reads shared configuration from the ServletContext.
7. Summary: Servlet’s Scalable Multithreaded Model
One Servlet Object → Multiple Requests → Multiple Threads
JVM manages threading → No burden on OS
ThreadPool improves response time and system throughput
ServletContext provides a shared space for common configurations
Key Takeaway (Interview Perspective)
Servlet technology shifted the model of dynamic web applications from process-based CGI to thread-based Java execution. This fundamental design change allowed Java applications to:
Scale efficiently
Reduce memory and CPU usage
Improve response time and system performance
That’s why Servlets are the preferred standard for modern Java-based server-side development.
Chapter 12: Servlet vs. JSP – Understanding Their Role in Java Web Applications
In Java-based web development, two foundational technologies are Servlet and JSP. At first glance, they may seem similar since both are capable of generating dynamic responses. However, their roles are distinctly different when placed within the layered architecture of a web application.
Servlets are server-side Java programs that handle incoming requests, process them, and return the appropriate response. To work with Servlets, a solid understanding of Java is required. Developers must know how to override lifecycle methods, work with request and response objects, and manage data flow. Since Servlet code is written entirely in Java, it tightly couples the processing and presentation logic unless a conscious effort is made to separate them.
JSP (Java Server Pages), on the other hand, is a technology primarily aimed at simplifying the creation of dynamic content. It is meant for presentation logic. A developer can build a fully functional JSP-based web page with only HTML knowledge and basic usage of JSP tags. In fact, Java knowledge is not mandatory to get started with JSP. The JSP pages are automatically compiled into Servlets by the container behind the scenes. This autocompilation mechanism makes development faster and easier, especially for changes in the user interface. Unlike Servlets, when a JSP is modified, there's no need to manually compile and redeploy—it happens automatically during runtime.
If we consider the MVC (Model-View-Controller) design pattern, which is a widely accepted architecture in enterprise application development, the place of Servlets and JSP becomes very clear. Servlets reside in the controller layer and are responsible for processing the incoming requests. JSPs are placed in the view layer and are used to present the output to the end user.
Chapter 13: MVC Architecture in Java Web Applications
The MVC architecture, short for Model-View-Controller, is a software design pattern that promotes separation of concerns in application development. It divides the application into three interconnected layers: the model, the view, and the controller. Each component has a dedicated responsibility, which improves modularity, makes the code easier to maintain, and helps manage complexity in large applications.
1. Controller – The Processing Layer
In Java web applications, the controller component is typically implemented using Servlets. The controller is responsible for handling all incoming client requests. It interprets the request, invokes the appropriate business logic, interacts with the model, and decides what data should be sent to the view for presentation. It does not interact with the database directly. Instead, it delegates that responsibility to the model layer. In this architecture, the Servlet acts as the gatekeeper—it filters, routes, and manages the control flow.
2. Model – The Persistence Layer
The model layer handles the actual interaction with the data source, usually a relational database. When a controller needs to retrieve, update, insert, or delete data, it calls the model. The model executes SQL queries through JDBC, or in more advanced setups, communicates via ORM tools like Hibernate or Spring Data JPA. This layer abstracts away the details of data access from the rest of the application. At this stage of development, most developers use JDBC to build their model logic. As they progress, they transition into using ORM frameworks for better maintainability and abstraction.
3. View – The Presentation Layer
The view is responsible for rendering the response that is finally sent back to the client. In Java web applications, JSPs are commonly used in the view layer. JSP files are embedded with HTML and, optionally, JSP tags to dynamically display the data fetched from the model. The key responsibility of the view is to display the data. It must not contain any business logic or database code. This separation ensures that designers and frontend developers can work on the view independently of backend developers who manage business logic and data access.
MVC Request-Response Flow – Explained Step by Step
Let’s understand how a client request flows through the MVC architecture using a typical Java web application.
Step 1: Client to Controller (Servlet)
A client, typically a browser or a web-enabled application, sends an HTTP request to the web server. This request is routed to the Servlet, which acts as the controller. The Servlet is mapped to a specific URL pattern, which makes it the entry point for the application.
Step 2: Controller to Model
The controller does not directly access the database. Instead, it communicates with the model. The controller passes the request parameters or commands to the model so that necessary operations can be performed on the data source.
Step 3: Model to Database
The model processes the request by sending SQL queries or commands to the database. It might retrieve data, insert new records, update existing information, or delete records based on the requirement.
Step 4: Database to Model
Once the database operation is completed, the results—usually in the form of a ResultSet—are returned back to the model. The model processes this raw data into a usable format such as Java objects or collections.
Step 5: Model to Controller
After receiving and preparing the data, the model returns the information to the controller. The controller now has everything it needs to respond to the request.
Step 6: Controller to View (JSP)
The controller forwards this data to a JSP page. This is done using mechanisms like RequestDispatcher’s forward()
method. The JSP is now responsible for presenting this data to the end user in a user-friendly and visual format.
Step 7: View to Client
Finally, the JSP renders the dynamic HTML content and sends the response back to the client. The browser interprets the HTML and displays the output to the user.
Optional Flow: View Accessing the Model
There are cases where the JSP might directly attempt to access the model to display or modify data. While technically possible, it is discouraged in good design practice. Direct interaction between the view and the model violates the separation of concerns principle. The model should always be accessed through the controller.
Summary of MVC Responsibilities and Technologies
Let’s summarize the core responsibilities and the technologies typically used in each layer:
Controller: Handles all incoming requests and routes them appropriately. Implemented using Servlets.
View: Handles user interface and display. Implemented using JSPs.
Model: Handles all business logic and database operations. Initially implemented using JDBC, later replaced by Hibernate or Spring Data JPA in modern applications.
This clean division ensures a scalable, testable, and maintainable application structure.
Conclusion: Why MVC Matters in Java Web Development
Understanding the MVC pattern is not just an academic requirement; it is a practical necessity in real-world software engineering. Large-scale applications demand code separation, reusability, and team collaboration. MVC provides exactly that. It allows frontend developers to focus purely on UI, backend developers to concentrate on business logic, and database specialists to handle persistence without crossing boundaries.
In Java web applications, the Servlet-JSP combination is the most classic example of MVC. With Servlets as controllers and JSPs as views, the architecture becomes modular. As the complexity of applications increases, you can introduce frameworks like Spring MVC, which formalizes this pattern even more strictly.
14. Tomcat Server Architecture – A Complete Theory Explanation
Apache Tomcat is a widely-used open-source web server and servlet container created by the Apache Software Foundation. It serves as a lightweight alternative to full Java EE servers, offering just the right components needed to deploy and run Java-based web applications, especially those using Servlets and JSPs (JavaServer Pages).
Let’s understand how the internal architecture of Tomcat is structured, based on the diagram.
1. Tomcat Server – The Entire Software Environment
At the outermost level in the diagram, we see the Tomcat Server. This represents the entire system or environment we install and run on our machines to serve web applications. The Tomcat server acts both as a web server and a servlet/JSP container.
2. Web Server Layer – First Interface to Clients
Inside the Tomcat Server, there is a layer labeled webserver. This is the component responsible for handling HTTP requests from clients (like browsers). The web server checks the type of request received:
If the request is for static content (e.g., HTML, CSS, JavaScript, or images), the web server itself responds directly with the file.
If the request is for dynamic content (like a
.jsp
or.do
file or any servlet-mapped URL), it forwards the request to the web container.
This division of responsibility ensures better performance and separation between serving static and dynamic content.
3. Web Container – The Runtime for Dynamic Java Content
The webcontainer label in the diagram is the heart of the Tomcat architecture. This is where Java dynamic web components are executed.
The web container is also called the Servlet/JSP container. It provides the environment to run servlet and JSP code securely, efficiently, and according to the servlet specification. Within the web container, Tomcat further divides functionality into two specialized sub-containers:
4. Servlet Container or Servlet Engine (CATALINA)
On the left side of the web container, we see a box labeled:
ServletContainer
or
Servlet Engine
(CATALINA)
This is the component responsible for executing Java Servlets. It is internally named Catalina in Tomcat. When a request maps to a servlet (like /
login.do
), the servlet container performs the following actions:
Loads the corresponding servlet class from the deployed application
Instantiates the servlet object (if not already done)
Calls lifecycle methods:
init()
,service()
, anddestroy()
at appropriate timesHandles HTTP methods like GET, POST via
doGet()
anddoPost()
Sends back a response generated by the servlet
Catalina is the core of Tomcat’s servlet processing engine and manages all servlet-based executions.
5. JSP Container or JSP Engine (JASPER)
On the right side of the web container, another box is labeled:
JSP Container
or
JSP Engine
(JASPER)
This component is dedicated to handling JavaServer Pages (JSP). The JSP container is called Jasper in Tomcat.
Here’s how Jasper works behind the scenes:
When a
.jsp
file is requested by a client (e.g.,home.jsp
), the JSP engine takes over.Jasper first translates the JSP page into an equivalent Java servlet class.
Then, it compiles that servlet into bytecode.
Finally, it delegates execution to the Servlet Engine (Catalina).
So, even though it starts as a JSP, after translation and compilation, it behaves like any other servlet and is executed by Catalina. This ensures reusability of the servlet engine and follows Java EE standards.
6. Combined Architecture: How Components Work Together
Now, combining all these layers from the diagram:
The Tomcat server provides the environment.
The web server listens for HTTP requests.
The web container (inside the web server) handles dynamic web content.
Within the web container:
CATALINA handles servlets.
JASPER handles JSPs, compiles them to servlets, and forwards them to Catalina.
This layered, modular structure allows Tomcat to efficiently serve both static and dynamic content while adhering to the servlet and JSP specifications.
Why This Separation Matters – Real World Understanding
This separation into Catalina and Jasper ensures a clean architectural model. Consider the following:
If you are building a pure Servlet-based backend application (like a REST API), your code runs purely within Catalina.
If you're building a JSP-based dynamic web page, Jasper translates and compiles your JSP into a servlet once, and then Catalina executes it.
This structure helps in performance tuning, maintenance, and modularity of the application, allowing Tomcat to scale better.
Supporting Components (as per your notes)
Tomcat installation also includes:
webapps/
directory: Where we deploy our WAR files or exploded web apps.lib/
directory: Contains essential JAR files likeservlet-api.jar
, used during compilation and runtime for Servlets/JSP.
These support files ensure that the above architecture runs smoothly without external dependencies.
Conclusion
The image you've provided beautifully captures the internal architecture of Tomcat, highlighting how:
The webserver acts as the gatekeeper,
The webcontainer houses the logic,
And Catalina and Jasper work together to handle Servlet and JSP requests respectively.
Understanding this architecture is crucial for Java web developers and for interviews, as it lays the foundation for how Java web applications run on a server.
14.2 Structure of Deployed Application in Tomcat
Each web application inside the webapps
folder must follow a specific structure. Let’s say you have an app called firstApp
. Inside webapps
, create a folder named firstApp
, and inside it, create a WEB-INF
folder. This WEB-INF
directory is mandatory and protected—it cannot be accessed directly from the browser. Inside WEB-INF
, include:
web.xml
– the deployment descriptor that maps servlet names to classes.classes/
– where all your compiled.class
files (like servlets) go.lib/
– for any application-specific JAR files.
So the structure becomes:
webapps/
└── firstApp/
└── WEB-INF/
├── web.xml
├── classes/
└── lib/
15. Developing a Web Application Using Servlet
To build a web application:
Create Servlet by extending
HttpServlet
.Override
doGet()
ordoPost()
method.Package it in a
.war
file.Deploy inside Tomcat’s
webapps
directory.Access via browser:
http://localhost:8080/yourapp/yourservlet
16. Summary of Servlet API Packages
javax.servlet.*
Servlet
(Interface)GenericServlet
(Abstract class)ServletRequest
,ServletResponse
ServletConfig
,ServletContext
RequestDispatcher
javax.servlet.http.*
HttpServlet
(Abstract class)HttpServletRequest
,HttpServletResponse
HttpSession
,Cookie
, etc.
✅ Final Thoughts
In this chapter, we explored the complete fundamentals of Servlet-based Java web development. We understood where Servlet fits in the ecosystem of Java, the difference between web and distributed applications, static vs. dynamic content, and the significance of Servlet API. We also looked into why Servlet is superior to CGI and why JSP complements Servlet in MVC architecture.
In the next chapter of this series, we will dive deeper into Servlet Lifecycle, including how requests are received, processed, and responses sent back with hands-on code examples, configuration in web.xml, and annotations.
Stay tuned.
Subscribe to my newsletter
Read articles from Rohit Gawande directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rohit Gawande
Rohit Gawande
🚀 Tech Enthusiast | Full Stack Developer | System Design Explorer 💻 Passionate About Building Scalable Solutions and Sharing Knowledge Hi, I’m Rohit Gawande! 👋I am a Full Stack Java Developer with a deep interest in System Design, Data Structures & Algorithms, and building modern web applications. My goal is to empower developers with practical knowledge, best practices, and insights from real-world experiences. What I’m Currently Doing 🔹 Writing an in-depth System Design Series to help developers master complex design concepts.🔹 Sharing insights and projects from my journey in Full Stack Java Development, DSA in Java (Alpha Plus Course), and Full Stack Web Development.🔹 Exploring advanced Java concepts and modern web technologies. What You Can Expect Here ✨ Detailed technical blogs with examples, diagrams, and real-world use cases.✨ Practical guides on Java, System Design, and Full Stack Development.✨ Community-driven discussions to learn and grow together. Let’s Connect! 🌐 GitHub – Explore my projects and contributions.💼 LinkedIn – Connect for opportunities and collaborations.🏆 LeetCode – Check out my problem-solving journey. 💡 "Learning is a journey, not a destination. Let’s grow together!" Feel free to customize or add more based on your preferences! 😊