-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
311: An Introduction to Servlets and the Servlet Lifecycle
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()anddoPost()). - 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
doGetmethod that looks for two parameters:value(the number) andunit(either "C" or "F"). - If
unitis "C", convert the value to Fahrenheit:(C * 9/5) + 32. - If
unitis "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
valueparameter 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.
There are no comments for now.