Servlets in Java: Servlet Types, Lifecycle, and Practical Servlet Programs
By Rohan Vats
Updated on Jan 10, 2025 | 24 min read | 10.6k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jan 10, 2025 | 24 min read | 10.6k views
Share:
Table of Contents
Java Servlets in Java are a fundamental technology for server-side programming, essential for building scalable and dynamic web applications. They handle client requests and generate responses, enabling robust backend functionality.
This blog introduces you to servlet in Java, covering their lifecycle and the different types of servlet available. Now, let’s dive deeper into the world of Java Servlets and explore their features, lifecycle, and how they transform the way web applications are built.
Java Servlets are server-side components that act as intermediaries between clients and servers, processing requests and generating dynamic responses. A servlet in Java is essential for creating efficient, scalable, and interactive web applications.
Let’s have a quick look at the main features of Java servlets:
Key Points:
Enterprise-Level Use: Vital for developing scalable enterprise applications with enhanced performance and functionality.
Servlets streamline server-side programming, making them indispensable for web developers aiming to create dynamic and high-performing web solutions.
The servlet in Java is built on the request-response model, where clients send requests, and the server processes them using servlets to generate responses. It ensures efficient client-server communication, making it essential for dynamic web applications.
Here is a quick look at the main components of a Java servlet architecture:
Key Components:
In the world of server-side programming, servlet in Java is a core component for creating dynamic and scalable web applications. Java servlets rely on key classes and interfaces to simplify their development and enhance reusability.
Here is a quick look at the various key classes and interfaces of Java servlets:
Key Classes and Interfaces:
Example: Implementing a Servlet Program in Java Using HttpServlet
Here’s a simple servlet program in Java that handles HTTP GET requests by overriding the doGet() method.
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
}
}
Explanation of Key Elements:
1. Extending HttpServlet:
The class extends HttpServlet, which allows it to handle HTTP requests such as GET, POST, etc.
2. doGet() Method:
Setting Content Type:
response.setContentType("text/html");
Writing Response Using PrintWriter:
PrintWriter out = response.getWriter();
3. HTML Content:
Steps to Deploy:
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.
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 integral to handling HTTP requests and responses in a web application. A servlet in Java processes client requests using GET or POST methods, delivering dynamic content or delegating tasks to other components like JSPs.
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.
The servlet in Java often acts as the controller in the Model-View-Controller (MVC) design pattern.
Example: Servlet as a Controller
The servlet processes user requests, retrieves data from the model, and forwards it to a JSP view.
Code:
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);
}
}
JSP Code (view.jsp):
<html>
<body>
<h1>Model Data:</h1>
<p>${data}</p>
</body>
</html
Expected Output:
When the MVCServlet is accessed via a GET request:
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.
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 robust 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: JSP vs Servlet: Difference Between JSP & Servlet
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.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Servlets and JSP (JavaServer Pages) serve different purposes in web development. Understanding their strengths helps you choose the right tool for your application.
Servlets: Backend Logic and Control
Use When:
Example:
A servlet processes user login data, validates credentials, and redirects to a dashboard.
JSP: Presentation and Dynamic Content
Use When:
Example:
A JSP page renders a user’s dashboard with personalized greetings and fetched data from the database.
When to Combine Servlets and JSP?
Use servlets for backend logic and JSP for rendering the front-end, creating a seamless Model-View-Controller (MVC) architecture.
Example:
A servlet fetches product details from a database, and a JSP page displays them in a catalog layout.
Now that you’re familiar with the types of Java servlets let’s move on to writing and deploying your first servlet program to see them in action.
Creating and deploying your first servlet program in Java is a crucial step in understanding server-side programming. This section walks you through setting up the environment, writing the servlet, deploying it on a server, and testing the functionality.
Follow these steps to prepare for servlet in Java development:
Here’s a simple servlet example that prints "Hello, World!" in the browser:
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>");
}
}
Here are the basic steps required to deploy the servlet:
Place the Servlet Class:
Save the compiled .class file in the WEB-INF/classes directory of your web application.
Configure the Deployment Descriptor (web.xml):
<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>
Start the Server:
Launch Tomcat and access the servlet at http://localhost:8080/YourAppName/hello.
Follow these steps to check your servlet:
Expected Output:
Servlets can also be deployed to a cloud environment, increasing their efficiency. Let’s see how this works.
Deploying servlets to a cloud platform ensures scalability, reliability, and global accessibility. Platforms like AWS and Google Cloud Platform (GCP) provide the necessary tools and infrastructure to host and manage servlet-based applications efficiently.
Let’s have a look at both one by one:
Deploying on AWS Elastic Beanstalk
Deploying on Google Cloud Platform (GCP)
1. Install Google Cloud SDK:
2. Prepare Your Servlet Application:
3. Create a Google App Engine Project:
4. Deploy the Application:
Use the command:
gcloud app deploy
5. Access Your Application:
This step-by-step guide ensures you understand the process of creating and deploying types of servlet for different use cases. Once you’ve mastered this, you can build more advanced servlet programs in Java for dynamic web applications.
Creating and deploying your first servlet program in Java involves a structured process, from setting up your environment to writing and testing your servlet. This section will help you understand each step with practical insights and best practices to ensure a smooth learning experience.
Before diving into servlet development, it’s crucial to set up a robust environment. This includes installing Java tools, configuring an IDE, and preparing a servlet container like Apache Tomcat.
Let’s have a look at the necessary steps:
Steps:
With your development environment ready, the next step is to create a well-organized project structure to streamline servlet development.
A well-structured project ensures clean and efficient servlet development. Follow these steps to set up your project and prepare for deployment.
Steps:
Also Read: 45+ Best Java Project Ideas for Beginners in 2025 with Source Code & Best Practices.
Once the project structure is in place, you can start writing the servlet code that defines the core functionality of your application.
Servlets are the core components for handling client requests and generating dynamic responses. Here’s how to write a basic servlet in Java.
Code Example: Basic Servlet
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/myfirst")
public class MyFirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().write("<h1>Welcome to My First Servlet</h1>");
}
}
Highlights:
After crafting your servlet code, the next step is to build and deploy your application to a server for execution.
Once your servlet code is ready, the next step is to compile, package, and deploy it on a servlet container like Apache Tomcat.
Steps:
With the servlet deployed, it’s time to test its functionality to ensure it handles requests and generates the expected responses.
Testing ensures your servlet functions as expected. You can use a browser or tools like Postman for verification. Let’s check out the necessary steps:
Steps:
1. Access the Servlet:
2. Verify the Output:
3. Test with Query Parameters:
Enhance your servlet to handle dynamic input:
String name = request.getParameter("name");
response.getWriter().write("<h1>Welcome, " + name + "!</h1>");
Example URL: http://localhost:8080/YourProjectName/myfirst?name=Priya
Expected Output:
During testing, you may encounter issues or opportunities for improvement—this is where debugging and enhancing your servlet comes into play.
Debugging is essential for resolving deployment issues, while enhancements improve functionality and user experience. Here are a few tips to keep in mind:
Tips:
After fine-tuning your servlet, adopting best practices will help you maintain clean, secure, and efficient code for long-term success.
Follow these best practices to write clean, secure, and maintainable servlet programs:
After learning the steps to write and deploy a servlet program, it’s essential to understand the servlet lifecycle, which governs how servlets are initialized, executed, and destroyed.
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 consists of three key stages—Initialization, Request Handling, and Destruction. Each stage plays a vital role in managing resources and ensuring efficient client-server interactions. Let’s explore these stages in detail.
1. Initialization (init() Method)
The initialization phase is the starting point of a servlet’s lifecycle. When a servlet is first loaded into the server’s memory, the init() method is called to set up essential configurations and resources. This ensures the servlet is ready to handle client requests.
What Happens:
Key Points:
Example Code:
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!");
}
}
With the servlet initialized, it’s now ready to process client requests dynamically through the next stage: Request Handling.
2. Handling Requests (service() Method)
The service() method lies at the heart of the servlet lifecycle, handling every client request. This phase is where the servlet processes data, generates responses and manages dynamic interactions between clients and the server.
What Happens:
Key Points:
Example Code:
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>");
}
}
After serving client requests, a servlet eventually reaches the final stage of its lifecycle: Destruction, where resources are cleaned up before removal.
3. Destruction (destroy() Method)
The destruction phase is the concluding stage of a servlet’s lifecycle. When a servlet is no longer needed, the destroy() method is invoked to release resources and perform cleanup tasks.
What Happens:
Key Points:
Example Code:
import javax.servlet.http.HttpServlet;
public class DestroyExampleServlet extends HttpServlet {
@Override
public void destroy() {
System.out.println("Servlet is being destroyed. Cleaning up resources...");
}
}
Also Read: Servlet Life Cycle in Java: Methods, Architecture, Comparison & Setup
Understanding these stages in detail allows developers to optimize resource usage and ensure their applications are reliable. Let’s visualize how these stages flow together in the servlet lifecycle.
The servlet lifecycle follows a structured flow to handle client-server interactions efficiently. This diagram illustrates the three stages: Initialization, Request Handling, and Destruction, and how they are interconnected.
Lifecycle Flow:
This structured approach to understanding the servlet lifecycle ensures better performance, scalability, and maintainability for web applications.
Now that you understand the servlet lifecycle let’s explore best practices to optimize servlet development for performance, security, and maintainability.
Developing Java servlets effectively requires a focus on performance, security, and maintainability. Following best practices ensures smooth and secure operation of your applications while improving user experience.
Here are a few best practices that you should ideally follow:
1. Validate User Input:
2. Use Thread-Safe Coding Practices:
3. Optimize Resource Cleanup in destroy():
4. Log Relevant Events and Exceptions:
Maintaining user interactions is key to building robust web applications. Here’s how servlets manage sessions effectively to ensure continuity across multiple client requests.
Session management ensures continuity of user interactions across multiple requests. Java servlets provide built-in support for session tracking via cookies, URL rewriting, and the HttpSession interface.
Let’s have a look at these techniques one by one:
Using HttpSession:
Store user-specific data like login status or preferences across requests.
Code Example:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
session.setAttribute("user", "Priya");
response.getWriter().write("<h1>Welcome, " + session.getAttribute("user") + "!</h1>");
}
}
Expected Output:
When the SessionExampleServlet is accessed via a GET request:
The output displayed in the browser will be:
<h1>Welcome, Priya!</h1>
This servlet demonstrates the use of HTTP sessions to store and retrieve user-specific data across multiple client requests.
Using Cookies and URL Rewriting:
Enable session continuity for users who have cookies disabled or when a session ID needs to be passed explicitly in URLs.
Session management is essential for a seamless user experience. Next, let’s focus on how to handle errors more gracefully.
Custom error pages enhance user experience by providing meaningful messages for different HTTP error codes or exceptions. They can be configured in web.xml.
Code Example:
<web-app>
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error500.html</location>
</error-page>
</web-app>
Expected Output:
Custom error pages improve usability, but exceptions must also be managed effectively to avoid crashes and data leaks.
Runtime errors can disrupt the flow of a servlet application, leading to poor user experience and potential system issues. To ensure smooth operation, handle exceptions effectively using try-catch blocks and robust logging mechanisms.
Key Points:
Example Code:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExceptionHandlingServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlingServlet.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
String value = request.getParameter("number");
int number = Integer.parseInt(value); // Potential for NumberFormatException
response.getWriter().write("<h1>Processed number: " + number + "</h1>");
} catch (NumberFormatException e) {
logger.error("Invalid number format: {}", e.getMessage());
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid input. Please provide a valid number.");
} catch (Exception e) {
logger.error("An unexpected error occurred: {}",
e.getMessage());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Something went wrong. Please try again later.");
}
}
}
Expected Output:
With effective error handling and session management in place, you can ensure robust and user-friendly servlet applications.
Now that you’ve explored servlet types, their lifecycle, and practical programs, let’s see how upGrad can help you master Java servlets and advance your skills further.
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://www.oracle.com/
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