1. What is a Servlet?
A Servlet is a Java class used to extend the capabilities of a server that hosts applications accessed via a request-response programming model.
- Runs on a web server or application server (e.g., Apache Tomcat).
- Handles HTTP requests (
GET,POST,PUT,DELETE) and generates dynamic responses (HTML, JSON, XML). - Acts as the Controller layer in traditional Model-View-Controller (MVC) architecture.
2. Servlet Architecture & Hierarchy
Servlets belong to the jakarta.servlet package (formerly javax.servlet).
Servlet (Interface)
│
GenericServlet (Abstract Class)
│
HttpServlet (Abstract Class)
│
YourCustomServlet (Concrete Class)
- Servlet Interface: Defines the core lifecycle methods.
- GenericServlet: Protocol-independent servlet implementation.
- HttpServlet: Provides HTTP-specific processing (
doGet,doPost, etc.).
3. Servlet Lifecycle
Managed entirely by the Servlet Container (e.g., Tomcat):
- Loading & Instantiation: Container loads the servlet class and creates an instance.
- Initialization (
init()): Called once when the servlet is created. Used for setup tasks (database connection setup, config loading). - Request Handling (
service()): Called for every incoming request. Routes requests to specific methods likedoGet()ordoPost(). - Destruction (
destroy()): Called once before the servlet is removed from memory. Used for cleanup.
4. Key Request Handling Methods
In an HttpServlet, you override specific methods depending on HTTP operations:
doGet(HttpServletRequest req, HttpServletResponse resp): HandlesGETrequests (retrieving data, rendering pages).doPost(HttpServletRequest req, HttpServletResponse resp): HandlesPOSTrequests (form submissions, sending sensitive/bulk data).doPut(),doDelete(): Handle RESTful updates and deletions.
5. Key Objects
HttpServletRequest: Provides access to client request data (form parameters, HTTP headers, cookies, request attributes).HttpServletResponse: Used to configure and send response data back to the client (content type, status codes, output stream/writer).ServletContext: Shared context across the entire application (global parameters, application attributes).ServletConfig: Servlet-specific initialization configuration defined inweb.xmlor annotations.
No comments yet.