Tutorials Logic, IN info@tutorialslogic.com

What Is Servlet? Beginner Guide, Uses & Examples

What Is Servlet? Beginner Guide, Uses & Examples

introduction is an important Servlet topic because it shows up in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

Focus on what problem introduction solves, where developers usually make mistakes, and how to verify the result with output, behavior, or a small test.

A strong understanding of introduction should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work.

What Is Servlet should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > introduction page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

Servlet Introduction

A Servlet is a Java server-side component that handles requests and generates responses. Servlets are mainly used to build dynamic web applications, process forms, create controller layers, manage sessions, return HTML or JSON, and connect browser requests to Java business logic.

A Servlet does not run like a normal main() program. It runs inside a Servlet container, also called a web container. The container receives HTTP requests, maps URLs to Servlets, creates request and response objects, manages the Servlet lifecycle, handles threading, and sends the final response back to the client.

  • Servlets are Java classes used for server-side web development.
  • They run inside a Servlet container such as Apache Tomcat, Jetty, WildFly, or GlassFish.
  • They commonly extend HttpServlet.
  • They handle HTTP methods such as GET, POST, PUT, and DELETE.
  • They are the foundation behind many Java web frameworks.

What Problem Do Servlets Solve?

A static HTML page always returns the same content. A Servlet can generate different responses based on request data, logged-in user, database records, form input, headers, cookies, or session state.

Requirement How Servlet Helps
Process a login form Reads username and password from the request.
Show user-specific content Uses session data or database records.
Return JSON for an API Sets response type and writes JSON output.
Upload a file Reads multipart request data.
Protect pages Works with filters, sessions, and authentication logic.
Connect to a database Calls service/DAO classes and returns results.

Servlet Container

The Servlet container is the runtime environment for Servlets. It sits between the web server and your Java code. Apache Tomcat is one of the most common Servlet containers for learning and deployment.

Container Responsibility Description
URL mapping Finds which Servlet should handle a request.
Lifecycle management Loads, initializes, calls, and destroys Servlet instances.
Thread management Allows one Servlet instance to serve many requests concurrently.
Request/response creation Provides HttpServletRequest and HttpServletResponse.
Session management Tracks users across requests with HttpSession.
Deployment Loads WAR files and web application configuration.

How a Servlet Request Works

When a browser or API client sends a request, the container follows a clear request-processing flow.

  • The client sends an HTTP request, such as GET /hello?name=Asha.
  • The web server receives the request and passes it to the Servlet container.
  • The container checks URL mappings and finds the matching Servlet.
  • If needed, the container creates and initializes the Servlet.
  • The container creates request and response objects.
  • The container calls service(), which dispatches to doGet(), doPost(), or another method.
  • The Servlet reads request data and writes the response.
  • The container sends the response back to the client.

Servlet API Hierarchy

The Servlet API defines the contracts and classes used by Servlet applications. For HTTP web applications, HttpServlet is the most important base class.

Type Purpose
Servlet Core interface that defines init(), service(), and destroy().
GenericServlet Protocol-independent abstract class.
HttpServlet HTTP-specific class with doGet(), doPost(), doPut(), and doDelete().
HttpServletRequest Represents incoming request data.
HttpServletResponse Represents outgoing response data.
HttpSession Stores user-specific data across requests.
ServletContext Stores application-wide information and resources.
ServletConfig Provides Servlet-specific initialization configuration.

javax.servlet vs jakarta.servlet

Older Java EE Servlet applications use javax.servlet packages. Newer Jakarta EE applications use jakarta.servlet. The core ideas are the same, but the package names and compatible server versions differ.

Stack Package Common Server Maven Artifact
Java EE / Servlet 4 javax.servlet Tomcat 9 javax.servlet-api
Jakarta EE / Servlet 5+ jakarta.servlet Tomcat 10+ jakarta.servlet-api

Maven Dependency Examples

Maven Dependency Examples
<dependency>
  <groupId>jakarta.servlet</groupId>
  <artifactId>jakarta.servlet-api</artifactId>
  <version>6.0.0</version>
  <scope>provided</scope>
</dependency>

javax.servlet vs jakarta.servlet

javax.servlet vs jakarta.servlet
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

Basic Servlet Example

A simple Servlet extends HttpServlet and overrides an HTTP method such as doGet(). The @WebServlet annotation maps the class to a URL.

After deployment, a request such as /hello?name=Asha calls this Servlet and returns an HTML response.

HelloServlet.java

HelloServlet.java
package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String name = request.getParameter("name");
    if (name == null || name.isBlank()) {
      name = "World";
    }

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    out.println("<!DOCTYPE html>");
    out.println("<html><body>");
    out.println("<h1>Hello, " + name + "!</h1>");
    out.println("</body></html>");
  }
}

Servlet Lifecycle

The Servlet container controls the lifecycle. A Servlet is typically created once and reused for many requests. This is important for performance, but it also means you must be careful with shared data.

Phase Method When It Runs
Loading Class loading The container loads the Servlet class.
Instantiation Constructor The container creates a Servlet object.
Initialization init() Called once before handling requests.
Request handling service() Called for each request.
HTTP handling doGet(), doPost() Called based on HTTP method.
Destruction destroy() Called once before the Servlet is removed.

Lifecycle Methods

Lifecycle Methods
@WebServlet(value = "/status", loadOnStartup = 1)
public class StatusServlet extends HttpServlet {

  @Override
  public void init() throws ServletException {
    System.out.println("StatusServlet initialized once");
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/plain");
    response.getWriter().println("Server is running");
  }

  @Override
  public void destroy() {
    System.out.println("StatusServlet destroyed once");
  }
}

HTTP Methods in Servlets

HttpServlet provides method handlers for common HTTP methods. You override the handler that matches the request type your Servlet should process.

HTTP Method Servlet Method Common Use
GET doGet() Read or display data.
POST doPost() Submit forms or create data.
PUT doPut() Update existing data.
DELETE doDelete() Delete data.
HEAD doHead() Return headers without body.
OPTIONS doOptions() Describe supported methods.

GET and POST Example

GET and POST Example
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.sendRedirect("login.html");
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");

    if ("admin@example.com".equals(email) && "secret".equals(password)) {
      response.getWriter().println("Login successful");
    } else {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.getWriter().println("Invalid credentials");
    }
  }
}

HTTP Methods in Servlets

HTTP Methods in Servlets
<form action="/login" method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email">

  <label for="password">Password</label>
  <input id="password" name="password" type="password">

  <button type="submit">Login</button>
</form>

Request Object

HttpServletRequest contains everything the client sent: URL path, parameters, headers, cookies, body data, session reference, and request metadata.

Reading Request Data

Reading Request Data
String name = request.getParameter("name");
String method = request.getMethod();
String uri = request.getRequestURI();
String userAgent = request.getHeader("User-Agent");
Cookie[] cookies = request.getCookies();
HttpSession session = request.getSession();

Response Object

HttpServletResponse controls what the server sends back. You can set content type, status code, headers, cookies, redirects, and response body.

Writing Responses

Writing Responses
response.setContentType("text/html;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);

PrintWriter out = response.getWriter();
out.println("<h1>Welcome</h1>");

Response Object

Response Object
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);

PrintWriter out = response.getWriter();
out.print("{\"status\":\"ok\"}");

Servlet Mapping

A Servlet must be mapped to one or more URL patterns. Mapping can be done with annotations or with web.xml. Annotation mapping is common for simple projects; web.xml is useful for centralized configuration.

URL Mapping

URL Mapping
@WebServlet(
  name = "ProductServlet",
  urlPatterns = {"/products", "/products/*"},
  loadOnStartup = 1
)
public class ProductServlet extends HttpServlet {
  // Servlet code
}

Servlet Mapping

Servlet Mapping
<servlet>
  <servlet-name>ProductServlet</servlet-name>
  <servlet-class>com.example.ProductServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>ProductServlet</servlet-name>
  <url-pattern>/products/*</url-pattern>
</servlet-mapping>

ServletContext and ServletConfig

ServletConfig stores configuration for one Servlet. ServletContext stores application-wide information shared across the web application.

Object Scope Common Use
ServletConfig Single Servlet Servlet-specific init parameters.
ServletContext Whole web app Application attributes, resources, logging, shared config.

Config and Context

Config and Context
String servletValue = getServletConfig().getInitParameter("mode");

ServletContext context = getServletContext();
String appName = context.getInitParameter("appName");
context.setAttribute("totalUsers", 100);

Session Management

HTTP is stateless, meaning each request is independent. Servlets use HttpSession, cookies, or URL rewriting to remember users across multiple requests.

Using HttpSession

Using HttpSession
HttpSession session = request.getSession();
session.setAttribute("userEmail", email);

String userEmail = (String) session.getAttribute("userEmail");

session.invalidate(); // logout

Thread Safety in Servlets

A Servlet instance can handle many requests at the same time using different threads. This means instance variables are shared and can cause bugs if they store request-specific data.

Thread Safety

Thread Safety
public class UnsafeServlet extends HttpServlet {
  private String currentUser; // shared by all requests

  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    currentUser = request.getParameter("user");
  }
}

Thread Safety in Servlets

Thread Safety in Servlets
public class SafeServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String currentUser = request.getParameter("user"); // local to this request
  }
}

Forward vs Redirect

Servlets can forward a request to another server-side resource or redirect the browser to a new URL. These actions look similar but behave differently.

Action Where It Happens Browser URL Changes? Use Case
Forward Server No Send request to JSP or another Servlet.
Redirect Client Yes Send user to another page after form submission.

Forward and Redirect

Forward and Redirect
// Server-side forward
request.getRequestDispatcher("/WEB-INF/views/profile.jsp")
       .forward(request, response);

// Client-side redirect
response.sendRedirect(request.getContextPath() + "/login");

Filters and Listeners Around Servlets

Filters and listeners are related Servlet technologies. A filter can run before and after a request reaches a Servlet. A listener reacts to lifecycle events such as application startup, session creation, or request creation.

Component Purpose Example
Servlet Handles a request and creates a response. ProductServlet
Filter Intercepts requests/responses. AuthenticationFilter, LoggingFilter
Listener Responds to lifecycle events. ServletContextListener

Servlets in MVC Architecture

In classic Java web MVC, the Servlet usually acts as the controller. It reads the request, calls service classes, stores results in request attributes, and forwards to a JSP view.

Servlet as Controller

Servlet as Controller
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
  private final ProductService productService = new ProductService();

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    List<Product> products = productService.findAll();
    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/views/products.jsp")
           .forward(request, response);
  }
}

Servlet vs JSP

Servlets and JSP are often used together. A Servlet is better for Java control logic. JSP is better for rendering HTML views. In MVC, Servlets should not contain large amounts of HTML, and JSP should not contain large amounts of Java logic.

Feature Servlet JSP
Primary role Controller and request handling. View rendering.
Written as Java class. HTML-like page with JSP tags.
Best for Business flow, validation, routing. Displaying dynamic HTML.
Bad use Writing huge HTML strings. Writing complex Java logic.

Servlet vs CGI

Before Servlets, CGI was a common approach for dynamic server-side content. Servlets improved performance by using a managed Java runtime and threads instead of starting a new process for each request.

Feature Servlet CGI
Execution model Container-managed, usually multi-threaded. Often one process per request.
Performance Efficient for repeated requests. Process startup can be expensive.
Session support Built-in APIs. Usually manual.
Portability Runs on Java Servlet containers. Depends on server and script environment.

Deployment Basics

Servlet applications are commonly packaged as WAR files and deployed to a Servlet container. The standard project structure keeps Java code, web resources, libraries, and configuration in known locations.

Typical Servlet Project Structure

Typical Servlet Project Structure
servlet-demo/
  src/main/java/com/example/
    HelloServlet.java
  src/main/webapp/
    index.html
    WEB-INF/
      web.xml
      views/
        products.jsp
  pom.xml

Where Servlets Are Used

  • Processing forms such as login, registration, search, and checkout.
  • Building controller layers for MVC web applications.
  • Returning JSON for Java-based APIs.
  • Managing sessions, cookies, and authentication flow.
  • Handling file upload and download.
  • Connecting web requests to service and database layers.
  • Supporting filters, listeners, and application lifecycle tasks.

Conclusion

Servlets are a core part of Java web development. They connect HTTP requests to Java code, read input, call application logic, manage sessions, and generate responses. Even when using frameworks such as Spring MVC, understanding Servlets helps you understand what happens underneath every Java web request.

To master Servlets, focus on the container, lifecycle, request and response objects, URL mapping, HTTP methods, sessions, thread safety, filters, listeners, MVC flow, and deployment. These concepts form the base for the rest of Java web programming.

What Is Servlet Java review example

What Is Servlet Java review example
class WhatIsServletReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("What Is Servlet: " + state);
    }
}

What Is Servlet guard example

What Is Servlet guard example
String value = null;
if (value == null) {
    System.out.println("What Is Servlet: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of introduction before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for introduction.
  • Write the rule in your own words after checking the example.
  • Connect introduction to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing What Is Servlet without the situation where it is useful.
RIGHT Connect What Is Servlet to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing What Is Servlet only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to What Is Servlet.
Evidence keeps debugging focused.
WRONG Memorizing What Is Servlet without the situation where it is useful.
RIGHT Connect What Is Servlet to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to introduction, then fix it and explain the fix.
  • Summarize when to use introduction and when another approach is better.
  • Write a small example that uses What Is Servlet in a realistic Servlet scenario.
  • Change one important value in the What Is Servlet example and predict the result first.

Frequently Asked Questions

A Servlet is a Java server-side component that runs inside a Servlet container and handles web requests by generating responses.

A Servlet container is the runtime that manages Servlets, request routing, lifecycle, threading, sessions, and deployment.

<code>doGet()</code> handles GET requests, usually for reading data. <code>doPost()</code> handles POST requests, usually for submitting data or changing server state.

Use <code>javax.servlet</code> with older Java EE/Tomcat 9 projects. Use <code>jakarta.servlet</code> with Jakarta EE/Tomcat 10+ projects.

Yes. Many Java web frameworks build on Servlet concepts, and understanding Servlets makes request handling, sessions, filters, and MVC flow much clearer.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.