Java Servlets by Example: Lifecycle, Practical Implementations, and Best Practices (2025)
By Rohan Vats
Updated on May 22, 2025 | 24 min read | 11.04K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on May 22, 2025 | 24 min read | 11.04K+ views
Share:
Table of Contents
Did you know that Java is still among the top 3 most popular programming languages among developers in 2025? Its widespread use powers scalable enterprise applications, with the servlet program in java remaining a foundational technology for server-side web development.
A servlet program in Java uses a structured lifecycle, init, service, and destroy to manage concurrent HTTP requests with thread safety and efficient resource handling. This guide details lifecycle methods, deployment workflows, and best practices, including input validation and session management.
You will also examine an example Java servlet showcasing dynamic response generation and error handling. Understanding these core concepts is essential for effective Java backend development in 2025.
Want to gain expertise in industry-relevant Java programming skills for DevOps and product deployment? upgrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!
Java servlets are server-side Java programs designed to handle client requests and generate dynamic content efficiently. They operate within a servlet container, managing HTTP protocols and supporting multithreading for high performance. Using Java servlets by example, you can build scalable web applications that integrate seamlessly with technologies like JavaScript and Node.js.
If you want to gather skills to understand the fundamentals of, the following courses can help you succeed.
Suppose you are developing an e-commerce platform targeting Indian users that requires fast, dynamic product listings and personalized recommendations powered by machine learning. Using Java servlets by example, you can handle user sessions efficiently while integrating with JavaScript frontends and Node.js microservices. This approach ensures responsive performance and a smooth shopping experience.
Now, having a clear understanding of the fundamental aspects of Java servlets, let’s look at the architecture of Java servlets in detail.
The Java servlet architecture follows a strict request-response model where clients send HTTP requests, and servlets process these requests to generate dynamic responses. This model optimizes communication between clients and servers, making it fundamental for building interactive web applications.
Using Java servlets, for example, you gain control over request handling with web technologies like HTML and scripting languages such as Bash scripting and PERL.
Imagine you’re building a customer support portal that collects input via HTML forms and processes it using servlets. By using Java servlets by example, you handle session management and validate user inputs securely. Meanwhile, you trigger Bash scripts for automated server health checks and utilize PERL scripts to process log files dynamically. This architecture ensures a responsive and maintainable web service tailored to your users’ needs.
Also read: 15 Essential Java Full Stack Developer Skills in 2025
Now, let’s explore Java's servlet classes and interfaces prominent within enterprise-related operations.
In server-side Java programming, servlets form the backbone of dynamic web applications by processing client requests and generating real-time responses. Java servlets by example utilize core classes and interfaces that streamline development, support HTTP protocols, and enhance integration with front-end frameworks like ReactJS and backend databases like MySQL.
Understanding these components ensures you can build scalable, maintainable applications with efficient database interactions using SQL queries.
Code Example:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// The WelcomeServlet class extends HttpServlet to handle HTTP-specific requests
public class WelcomeServlet extends HttpServlet {
// The doGet method handles GET requests from clients
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Setting the response content type to HTML
response.setContentType("text/html");
// Obtaining the PrintWriter object to write the response
PrintWriter out = response.getWriter();
// Writing the HTML response
out.println("<html><body>"); // Starting the HTML document
out.println("<h1>Welcome to Java Servlets!</h1>"); // Adding a heading
out.println("<p>This is an example of a servlet program in Java using HttpServlet.</p>"); // Adding a paragraph
out.println("</body></html>"); // Ending the HTML document
}
}
Output:
<html>
<body>
<h1>Welcome to Java Servlets!</h1>
<p>This is an example of a servlet program in Java using HttpServlet.</p>
</body>
</html>
When you access this servlet through a browser, it returns a clean HTML page with a heading confirming successful servlet execution. The paragraph briefly describes the servlet example, ensuring the response is clear and structured for further frontend or backend enhancements using ReactJS or MySQL.
Expected Output:
When this servlet is accessed via a browser using a GET request, the server responds with an HTML page containing the following:
This output demonstrates a basic servlet generating dynamic web content.
When you pair servlets with ReactJS on the frontend, servlets handle backend processing and database communication using SQL with MySQL. For example, servlets can accept REST API calls from ReactJS, process data, query MySQL databases, and respond with JSON. This layered architecture promotes separation of concerns and scalability.
Now that you’ve learned about the key classes and interfaces let’s explore how you can handle HTTP requests and responses dynamically.
Java servlets are fundamental components in server-side programming that handle HTTP requests and responses for web applications. They efficiently process client data through GET and POST, enabling dynamic content generation and seamless integration with front-end technologies like CSS and backend languages like C++ and C#. By learning Java servlets by example, you can build scalable web services that communicate smoothly with diverse client environments and technologies.
Imagine developing a search portal that accepts queries via a ReactJS frontend styled with CSS. The servlet handles GET requests, extracts query parameters, and forwards results to JSP pages. Backend processing utilizes C++ modules for advanced search algorithms, while C# services manage user authentication via POST requests. Applying Java servlets by example, this architecture supports modular, scalable, and efficient communication across languages and technologies.
Let us now have a look at GET and POST one by one:
GET requests are typically used to fetch data. Servlets can retrieve query parameters and generate responses dynamically.
Example: Handling a search request by retrieving user input from query parameters.
Code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String query = request.getParameter("query");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Search Results for: " + query + "</h1>");
out.println("<p>Displaying results...</p>");
out.println("</body></html>");
}
}
Expected Output:
When the SearchServlet is accessed via a GET request with a query parameter (e.g., ?query=Java), the server responds with an HTML page containing:
This servlet demonstrates handling user input via query parameters and dynamically generating a web page based on the input.
POST requests are used for submitting data securely. Servlets handle form submissions by validating and processing user inputs.
Example: Validating user login details.
Code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
if ("admin".equals(username) && "password123".equals(password)) {
out.println("<h1>Welcome, " + username + "!</h1>");
} else {
out.println("<h1>Invalid Credentials</h1>");
}
out.println("</body></html>");
}
}
Explanation of Parameters:
After understanding how to handle HTTP requests and responses, let’s see how you can enable seamless communication between servlets and JSPs.
Servlets can forward requests to JSPs using RequestDispatcher and share data with them.
Example: Forwarding user input to a JSP for display.
Code:
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello from Servlet!";
request.setAttribute("message", message);
RequestDispatcher dispatcher = request.getRequestDispatcher("display.jsp");
dispatcher.forward(request, response);
}
}
JSP Code (display.jsp):
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<h1>${message}</h1>
</body>
</html>
Expected Output:
When the ForwardServlet is accessed via a GET request:
The output in the browser will show:
<h1>Hello from Servlet!</h1>
This servlet demonstrates how to forward requests to a JSP and pass data for dynamic rendering in the response.
With servlet-JSP communication covered, let’s explore how you can integrate servlets into the MVC architecture for cleaner application design.
In Java web development, servlets often function as the controller within the Model-View-Controller (MVC) design pattern, managing client requests and coordinating data flow between the model and view. The Model layer contains business logic and data management, often connecting to databases using SQL or services implemented in languages like C++ or C#.
The View uses JSP to render HTML interfaces styled with CSS. Implementing Java servlets by example in this pattern improves application modularity, scalability, and maintainability.
Code Example:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class MVCServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "Data from Model Layer";
request.setAttribute("data", data);
RequestDispatcher dispatcher = request.getRequestDispatcher("view.jsp");
dispatcher.forward(request, response);
}
}
Output:
<html>
<body>
<h1>Model Data:</h1>
<p>${data}</p>
</body>
</html>
When the MVCServlet processes a GET request, it sets the data attribute and forwards the request to the view.jsp page. The JSP dynamically renders this data within an HTML structure, displaying the message inside the <p> tag. This separation ensures that business logic remains in the servlet, while presentation is handled by JSP, aligning with MVC principles.
The output in the browser will be:
<h1>Model Data:</h1>
<p>Data from Model Layer</p>
This example illustrates the Model-View-Controller (MVC) pattern, where the servlet acts as the controller, forwarding data to the JSP (view) for rendering.
Use Case:
Imagine you’re developing an enterprise dashboard where backend services written in C# and C++ handle complex computations and data aggregation. Using Java servlets by example, your servlet acts as the controller that fetches processed data from these services and forwards it to JSP views. This MVC approach allows your team to update business logic or UI components independently, enhancing scalability and maintainability in multi-technology environments.
Also Read: Java MVC Project [Step-By-Step Process Explained]
Having understood servlet classes and interfaces, let’s explore the types of Java servlets and how they address different application needs.
Java servlets offer a flexible and efficient framework for server-side programming tailored to handle diverse web application needs. Servlet in Java are classified into two primary types: GenericServlet and HttpServlet. Each serves unique purposes, empowering developers to create versatile, scalable, and effective web applications that meet specific requirements.
Let’s explore these servlet types in detail.
GenericServlet is a protocol-agnostic foundation for developing servlets in Java. It offers unmatched flexibility for handling a wide range of client requests, regardless of the communication protocol.
Let’s have a look at its features and usage.
Examples:
While GenericServlet lays the foundation for flexible request handling, many web applications require HTTP-specific capabilities. Let’s explore how HttpServlet fulfills these needs.
HttpServlet is a specialized extension of GenericServlet designed to simplify HTTP-specific tasks. It provides predefined methods like doGet() and doPost(), enabling developers to focus on application logic without reinventing request-handling mechanisms.
Let’s have a look at its features and usage.
Examples:
E-commerce Applications:
Banking Portals:
Content Management Systems (CMS):
Customer Support Systems:
Also Read: Top 22 Open Source Java Projects to Enhance Your Development Skills
After exploring the types of Java servlets, let’s compare servlets with JSP to understand their unique roles and when to use each in web development.
In Java web development, servlets and JSP serve distinct but complementary roles. Servlets excel in handling backend business logic, managing requests, sessions, and database interactions, often running on platforms like AWS Lambda or Azure App Services.
Conversely, JSP focuses on rendering dynamic web pages with embedded Java, CSS, and JavaScript for a responsive user interface. Combining them in an MVC architecture creates scalable, maintainable applications that integrate seamlessly with cloud services such as AWS and Azure Databricks.
Here’s a comprehensive difference among servlets, JSP, and combined MVC architectures:
Aspect | Servlets | JSP (JavaServer Pages) | Combined Use in MVC Architecture |
Purpose | Backend logic and control | Presentation and dynamic content | Servlets handle backend processing; JSP renders the front-end UI |
Use Cases | Handling HTTP requests and sessions | Displaying data generated by servlets | Example: Servlet fetches data; JSP displays it |
Example Scenario | A servlet validates user login credentials and redirects to a dashboard | A JSP page renders personalized greetings and data fetched from the databasE | A servlet retrieves product details from a MySQL database, then forwards to a JSP catalog page |
Integration with Cloud Services | Ideal for AWS Lambda functions handling serverless backend tasks and session management | JSP works with UI rendering on AWS-hosted web servers or Azure App Services | Combined MVC apps use AWS for compute and Azure Databricks for big data processing |
Technical Strengths | Effective request processing, session tracking, secure data handling | Simplifies UI rendering with embedded Java, supports CSS and JavaScript integration | Modular, maintainable architecture supporting diverse tech stacks |
If you want to gain expertise in Java and modern cloud computing architectures, check out upGrad’s Professional Certificate Program in Cloud Computing and DevOps. The program will help you build your DevOps skills along with proficiency in AWS, Azure, and more.
Also read: Top 9 Machine Learning APIs for Data Science You Need to Know About
Developing and deploying your first servlet program in java is fundamental to learning server-side web programming. This process involves configuring a Java development environment, writing servlet code following the servlet lifecycle, and deploying it on a servlet container such as Apache Tomcat. Learning these steps equips you with essential skills in session management in servlet and error handling in servlet, enabling scalable web applications.
Suppose you are tasked with building a user authentication module for a web application. Using your first servlet program in Java, you implement the servlet lifecycle methods to initialize resources and manage requests.
You integrate session management in servlet to track logged-in users and incorporate error handling in servlet to gracefully manage invalid login attempts. Deploying this on Apache Tomcat within your IDE allows for iterative testing and debugging, laying the groundwork for more complex enterprise-grade applications.
Creating your first servlet program in java introduces you to the core of server-side Java web development. This simple servlet responds to HTTP GET requests by sending a dynamic HTML response. Understanding this foundational example will help you grasp the servlet lifecycle and the basics of session management in servlet later on.
Here’s a step-by-step manner to write a servlet program in Java
Code Example:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().println("<html><body><h1>Hello, World!</h1></body></html>");
}
}
Output:
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
When you access this servlet via a web browser, it returns a well-formed HTML page displaying “Hello, World!” inside an <h1> tag. This confirms that the servlet successfully processed the GET request and sent dynamic content, demonstrating the essential behavior of a java servlet example.
Imagine you are beginning your journey in Java web development and want to verify your environment setup. Writing and deploying this servlet program in java helps you confirm that your server correctly handles HTTP requests. This foundational knowledge prepares you to implement more advanced features like session management in servlet and error handling in servlet.
Deploying your servlet program in java requires placing compiled classes correctly and configuring the deployment descriptor (web.xml). This configuration instructs the servlet container (e.g., Apache Tomcat) how to map URLs to your servlet, ensuring it’s accessible for HTTP requests.
Code Example:
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Output:
http://localhost:8080/YourAppName/hello
Upon deployment, navigating to the URL mapped to /hello triggers the servlet’s doGet() method. The browser displays the “Hello, World!” message confirming that Tomcat correctly routes requests to your servlet, showcasing the servlet lifecycle from initialization to request handling.
Consider deploying your first servlet program in java as part of a training exercise to understand deployment mechanics. Successfully configuring web.xml and accessing your servlet demonstrates proficiency in servlet configuration and lays the foundation for handling real-world tasks like integrating with AWS Lambda or Azure App Services.
Testing your servlet program in java ensures it responds correctly to HTTP requests. You can verify functionality through standard web browsers or API testing tools like Postman, simulating GET requests and inspecting the responses.
Code Example:
GET http://localhost:8080/YourAppName/hello
Output:
curl -X GET http://localhost:8080/YourAppName/hello
Output Explanation:
This GET request targets the URL pattern /hello mapped to your servlet in web.xml. When the servlet container (like Tomcat) receives this request, it invokes the doGet() method of your servlet program in java, which returns the dynamic HTML response "Hello, World!".
Deploying your servlet program in Java to cloud platforms ensures scalability, high availability, and global accessibility. Cloud providers like AWS and Google Cloud Platform (GCP) offer managed infrastructure and services to efficiently host and run servlet-based applications. Using containerization with Docker, orchestration with Kubernetes, and streaming with Apache Kafka can further enhance deployment flexibility, resilience, and real-time data processing capabilities.
Here are the steps for deploying servlets to a cloud environment:
Code Example:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().println("<html><body><h1>Hello, World from Cloud Deployment!</h1></body></html>");
}
}
Output:
<html>
<body>
<h1>Hello, World from Cloud Deployment!</h1>
</body>
</html>
Accessing the servlet URL hosted on AWS Elastic Beanstalk or GCP App Engine triggers the servlet's doGet() method, returning a dynamic HTML page confirming deployment. This response demonstrates proper handling of the servlet lifecycle within a cloud-managed servlet container, with opportunities to incorporate session management in servlet.
Suppose you develop a real-time analytics dashboard where servlets process incoming data streams, and Apache Kafka manages event-driven data flow. You containerize the application with Docker and orchestrate deployments using Kubernetes on AWS EKS. For example, you use Java servlets to deploy the servlet WAR to Elastic Beanstalk for global availability while integrating it with Kafka for asynchronous processing.
If you want to learn more about JavaScript, check out upGrad’s JavaScript Basics from Scratch. The 19-hour free certification will provide you with expertise on conditionals, variables, and more for organizational applications.
The servlet lifecycle in Java is designed to efficiently manage the creation, execution, and destruction of servlets, ensuring optimal use of server resources. This lifecycle has three primary stages: Initialization, Request Handling, and Destruction. Each stage plays a critical role in maintaining application stability and performance in various types of servlet.
Let’s dive into each stage in detail.
The servlet lifecycle defines how your servlet program in java initializes, handles client requests, and cleans up resources. Learning these stages, Initialization, Request Handling, and Destruction is critical for efficient resource use, effective session management in servlet, and proper error handling in servlet. Understanding this lifecycle improves application performance and reliability.
Code Example:
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class InitExampleServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("Servlet initialized and ready to handle requests!");
}
}
Output:
Servlet initialized and ready to handle requests!
Output Explanation:
When the servlet is loaded, the server logs the initialization message once, confirming the servlet setup phase completed successfully.
Code Example:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServiceExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().write("<h1>Request Handled: GET Method</h1>");
}
}
Output:
<h1>Request Handled: GET Method</h1>
Output Explanation:
When accessed via a browser or HTTP client, the servlet dynamically returns an HTML response indicating that the GET request was processed, demonstrating active request handling in the servlet lifecycle.
Code Example:
import javax.servlet.http.HttpServlet;
public class DestroyExampleServlet extends HttpServlet {
@Override
public void destroy() {
System.out.println("Servlet is being destroyed. Cleaning up resources...");
}
}
Output:
Servlet is being destroyed. Cleaning up resources...
Output Explanation:
This message logs when the servlet is unloaded, confirming resource cleanup aligned with proper error handling in servlet and lifecycle management.
Also read: Top 20 DevOps Practice Projects for Beginners with Source Code in 2025
Developing efficient and secure servlet programs in java demands adherence to best practices that enhance code maintainability, performance, and security. Proper project organization, input validation, and optimized resource management ensure your servlets handle requests reliably within the constraints of the servlet lifecycle.
Using modern features like annotations and session management in servlet mechanisms strengthens your application’s resilience and user experience.
Consider you’re developing an e-commerce platform using a servlet program in java. By organizing your codebase clearly, you streamline feature updates and bug fixes. You validate all user inputs to protect against malicious payloads, apply @WebServlet annotations for cleaner deployment, and manage user sessions securely to personalize shopping experiences. Logging provides insights into user behavior and system health, aligning with production-grade application standards and supporting the servlet lifecycle effectively.
Also read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
Servlets in Java implement HTTP request handling through distinct servlet types and a precise lifecycle to enable scalable, efficient server-side web processing. Understanding servlet lifecycle stages, initialization, request handling, and destruction ensures efficient resource management and reliable performance. To optimize your servlet programs, implement effective session management, validate inputs rigorously, and use annotations for streamlined configuration.
If you want to gather expertise in Java and other programming tools. These are some of the additional courses of upGrad that can help understand Java for software development and product deployment purposes. .
Curious which courses can help you gain expertise Java? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.
upGrad offers tailored learning programs designed to help Java professionals deepen their knowledge and advance their careers. These programs focus on core concepts like servlets, JSP, and practical implementation, ensuring a hands-on approach to mastering Java development.
Here are a few programs to get you started:
Program Benefits:
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
References:
https://softjourn.com/insights/is-java-still-used
408 articles published
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources