What is a Java Servlet?
A Java Servlet is a server-side program that runs on a web or application server. It sits between HTTP client requests (from browsers or other clients) and server-side resources like databases. Servlets can collect user input from web forms, retrieve records from databases, and dynamically generate web pages.
Servlets serve a similar purpose to CGI (Common Gateway Interface) scripts but offer several advantages:
- Better performance: Servlets run within the web server's address space, avoiding the creation of a separate process for each client request.
- Platform independence: Writen in Java, Servlets can run on any platform with a compatible Java environment.
- Security: The Java security manager enforces restrictions on the server, making Servlets trustworthy.
- Full access to Java libraries: Servlets can interact with databases, applets, or other software via sockets, RMI, and other mechanisms.
Servlet Architecture
A Servlet is part of the web application layer, receiving client requests and generating responses. The architecture typically involves:
- Client: sends HTTP requests.
- Web Server / Servlet Container: manages Servlet lifecycle, dispatches requests.
- Servlet: processes requests and returns responses.
- Backend Resources: databases, services, etc.
Core Tasks of a Servlet
A Servlet performs the following tasks:
- Read explicit data sent by the client (e.g., HTML form input).
- Read implicit HTTP data (cookies, media types, compression formats).
- Process data and generate results (database queries, computations, Web service calls).
- Send explicit response data (HTML, XML, images, etc.) to the client.
- Send implicit HTTP response details (content type, cookies, caching instructions).
Servlet Packages
Java Servlets are implemented using the javax.servlet and javax.servlet.http packages. These are part of the Java Enterprise Edition (Java EE). The classes in these packages implement the Servlet and JSP specifications.
Once the Servlet API is installed and added to the classpath, Servlets can be compiled using any standard Java compiler.
Servlet Lifecycle
The lifecycle of a Servlet is defined from creation to destruction. It follows these stages:
- Initialization:
init()is called once when the Servlet is first created. - Request Handling:
service()is called for each client request. - Destruction:
destroy()is called once when the Servlet is taken out of service. - Garbage Collection: The JVM garbage collector eventually cleans up the Servlet object.
The init() Method
init() is called exactly once, either when the Servlet is first requested or at server startup (if configured). It handles one-time initialization, loading resources, or establishing connections.
public void init() throws ServletException {
// Initialization code
}
After initialization, each client request runs in a separate thread, but all share the same Servlet instance.
The service() Method
service() is the main method for handling requests. The container calls it, passing the request and response objects. It determines the HTTP method (GET, POST, etc.) and deelegates to the appropriate handler (doGet, doPost, etc.).
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
// Typically, the container manages delegation
}
As a developer, you rarely override service() directly. Instead, you implement doGet() or doPost().
doGet()
Handles HTTP GET requests (normal URL requests or forms without a specified method).
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Process GET request
}
doPost()
Handles HTTP POST requests (from forms with method=POST).
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Process POST request
}
The destroy() Method
destroy() is called once at the end of the Servlet's lifecycle. It is used for cleanup: closing database connections, stopping background threads, saving state (e.g., counters to disk), etc.
public void destroy() {
// Cleanup code
}
After destroy(), the Servlet object becomes eligible for garbage collection.
Typical Lifecycle Flow
The following illustrates a typical request scenario:
- An HTTP request arrives at the server.
- The servlet container (e.g., Tomcat) receives the request.
- If the Servlet is not yet loaded, the container loads it and calls
init(). - The container calls
service()for the request, which may run in a new thread. - Additional requests create new threads, all using the same Servlet instance.
- When the application is shut down or the Servlet is removed,
destroy()is called.