Skip to Content
Course content

311: An Introduction to Servlets and the Servlet Lifecycle

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of a Servlet like a specialized clerk working at a government office—say, the Department of Motor Vehicles. The office building is your Web Container (like Tomcat). The building provides the electricity, the desks, and the front door, but it doesn't actually know how to process a driver's license renewal. For that, it needs a clerk who knows the specific rules of the road.

Here is how that maps to the code you're about to write:

  • The Hiring Process (init): The clerk doesn't just teleport into the office. They are hired and trained once. They set up their desk and get their stamps ready. This is the init() method.
  • Processing the Line (service): Once the office opens, the clerk handles a stream of people. One person asks for a registration; the next asks for a license. The clerk handles the request and hands back a document. This is the service() method (and its children, doGet() and doPost()).
  • Retirement (destroy): When the office closes forever or the clerk retires, they clear their desk and turn off the lights. This is the destroy() method.

The Ritual of the Servlet Lifecycle

In a standard Java app, you control the main() method. In a Servlet, you give up that control. The Web Container is the boss. It decides when to instantiate your class and when to kill it. I've seen a lot of developers try to put heavy initialization logic inside doGet(), but that's a mistake—you're essentially retraining your clerk every single time a customer walks through the door.

The init() method runs exactly once. Use it for things that don't change, like loading a configuration file or establishing a database connection pool. Then, the container calls service() for every single HTTP request. If it's a GET request, it routes to doGet(); if it's a POST, it goes to doPost().

Handling a Real Request: The Currency Converter

Let's look at a practical example. Instead of a boring "Hello World," let's imagine a Servlet that converts USD to EUR. We need to grab a value from the URL, do some math, and send back a response.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CurrencyConverterServlet extends HttpServlet {
    private double exchangeRate;

    // This runs once when the servlet is first loaded
    public void init() throws ServletException {
        // Imagine we fetch this from a database or API in a real app
        this.exchangeRate = 0.92; 
        System.out.println("Converter initialized with rate: " + exchangeRate);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // Pull the 'amount' parameter from the URL (e.g., ?amount=100)
        String amountStr = request.getParameter("amount");
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        if (amountStr == null || amountStr.isEmpty()) {
            out.println("<h2>Please provide an amount!</h2>");
        } else {
            try {
                double usd = Double.parseDouble(amountStr);
                double eur = usd * exchangeRate;
                out.println("<h2>$" + usd + " USD is equal to €" + eur + " EUR</h2>");
            } catch (NumberFormatException e) {
                out.println("<h2>Invalid number format!</h2>");
            }
        }
    }

    public void destroy() {
        System.out.println("Cleaning up resources before the servlet is unloaded.");
    }
}

Where the Magic Actually Happens

Notice that I extended HttpServlet. This is key. By doing that, I'm telling the container that this class is capable of handling HTTP traffic. The HttpServletRequest object is your window into the client—it tells you what they want. The HttpServletResponse object is your megaphone—it's how you tell the client what happened.

One thing to keep in mind: Servlets are singleton-like by default. The container usually creates only one instance of CurrencyConverterServlet and uses it to handle hundreds of simultaneous requests. This means you must be very careful with "instance variables." If you store user-specific data in a class-level field, you'll end up leaking one user's data to another. Keep your request-specific logic inside the doGet or doPost methods.




📋 Practical Task

Build a Dynamic Temperature Conversion Servlet

Your task is to create a Servlet named TempConverterServlet that can convert temperatures between Celsius and Fahrenheit. The Servlet should be able to handle two different scenarios based on a URL parameter.

Requirements:

  • Implement a doGet method that looks for two parameters: value (the number) and unit (either "C" or "F").
  • If unit is "C", convert the value to Fahrenheit: (C * 9/5) + 32.
  • If unit is "F", convert the value to Celsius: (F - 32) * 5/9.
  • Use the init() method to print a message to the server console indicating that the Temperature Converter is online.
  • Handle the case where the value parameter is missing or not a valid number by returning a user-friendly HTML error message.
  • Ensure the response content type is set to text/html.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.