What is Servlet?

 I have been studying Java and Spring. Even though I have been using Servlet, I didn't know what it exactly is and how it actually works. This time, I dived into it.


1. The Essence of Servlets: What Are They?

What Is a Servlet?

At its core, a Servlet is a Java program designed to run on the server side. Its job? To handle requests (usually HTTP requests from a web browser) and generate dynamic responses (like HTML or JSON) for the client. Think of it as the engine that powers interactive web pages, whether it’s processing a login form or fetching data from a database.

  • Name Origin: The word "Servlet" is a blend of "Server" and "Applet" (a small Java program that runs on the client side). It’s a "small program" that lives and works on the server.
  • Where It Lives: Servlets are part of Java EE (Enterprise Edition) and are defined in the javax.servlet and javax.servlet.http packages.

So, What Exactly Is It?

A Servlet is just a Java class, but not your typical one. Unlike a standalone Java program, it’s built to run in a web server environment and interacts with clients using the HTTP protocol.

  • Example: Imagine a user submits a login form. The Servlet grabs the username and password, checks them against a database, and sends back an HTML page saying "Login Successful!" That’s a Servlet in action.

The Big Idea

Servlets were created as a replacement for CGI (Common Gateway Interface), an older technology that launched a new process for every request slow and inefficient. Servlets, on the other hand, use a thread-based model, making them faster and more scalable. This shift was a game-changer for web development.


2. The Anatomy of a Servlet: Structure and Components

Servlets are built on a foundation of specific interfaces and classes. Let’s break them down.

Key Components

  1. Servlet Interface
    • The foundation of all Servlets. It defines the basic contract every Servlet must follow.
    • Key Methods:
      • init(ServletConfig): Called once to initialize the Servlet.
      • service(ServletRequest, ServletResponse): Handles incoming requests.
      • destroy(): Cleans up when the Servlet shuts down.
      • getServletConfig(), getServletInfo(): Provide configuration and metadata.
  2. GenericServlet Class
    • An abstract implementation of the Servlet interface.
    • It’s protocol-agnostic, meaning it could theoretically work with non-HTTP protocols (though we rarely use it that way).
  3. HttpServlet Class
    • The star of the show for web developers. It extends GenericServlet and is tailored for HTTP.
    • Key Methods:
      • doGet(): Handles GET requests (e.g., loading a webpage).
      • doPost(): Handles POST requests (e.g., form submissions).
      • doPut(), doDelete(): For other HTTP methods.

A Simple Example

Here’s a basic Servlet that responds with a friendly message:

public class MyServlet extends HttpServlet
    @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws     
    IOException
        resp.setContentType("text/plain");
       resp.getWriter().write("Hello from Servlet!");
    }
}
  • When a GET request hits /myServlet, it sends back "Hello from Servlet!" as plain text. Simple, right?

3. Servlets and Their Best Friend: The Servlet Container

Servlets don’t run on their own. They need a Servlet Container (aka Web Container) to bring them to life. Think of Apache Tomcat, a popular choice, as the home where Servlets live and work.

What Does the Servlet Container Do?

  • Manages Servlets: Loads the Servlet class, creates an instance, and oversees its lifecycle.
  • Maps Requests: Connects URLs (like /login) to the right Servlet, using web.xml or @WebServlet annotations.
  • Handles Threads: Spawns a thread for each client request to call the Servlet’s service() method.
  • Supports I/O: Provides HttpServletRequest and HttpServletResponse objects to make reading requests and writing responses a breeze.

How It Flows

  1. A browser requests http://localhost:8080/app/login.
  2. Tomcat finds the Servlet mapped to /login in the /app context.
  3. The Servlet’s doGet() or doPost() runs, depending on the request type.
  4. The Servlet crafts a response, and Tomcat sends it back to the browser.

4. The Servlet Lifecycle: A Deeper Look

Servlets have a well-defined life, managed entirely by the container. Here’s how it plays out:

Creation and Initialization

  • When a client makes the first request, the container loads the Servlet class and creates an instance.
  • The init() method runs once to set things up (e.g., connecting to a database).
  • After this, the Servlet stays in memory for reuse, no need to recreate it every time.

Request Handling

  • For every request, the service() method is called.
  • In HttpServlet, it delegates to methods like doGet() or doPost() based on the HTTP method.
  • Example: A <form method="post"> triggers doPost().

Destruction

  • When the server shuts down or the app is redeployed, destroy() is called.
  • This is the cleanup phase like closing files, disconnecting from resources, etc.

Cool Facts

  • Singleton: Only one instance of a Servlet exists per class.
  • Multithreaded: Multiple requests? Each gets its own thread, sharing the same Servlet instance.

Comments

Popular posts from this blog

@ModelAttribute vs @RequestBody in Validation

Side Project(a self-imposed 3-day "Hackathon" challenge)

Google: The King is Back