Servlet Application Flow
Servlets are server-side Java programs that process client requests and generate dynamic web content. Below is a typical flow of a Servlet application:
- The client sends a request to the web server.
- The web server passes the request to the appropriate servlet container (e.g., Tomcat).
- The servlet container identifies the corresponding servlet based on the request URL.
- If the servlet is not loaded, it is instantiated and initialized.
- The servlet processes the client request via the
service()method. - The response is generated and sent back to the client.
- The servlet remains in memory to handle further requests, or it may be destroyed by the container if idle.
Servlet Life Cycle
The servlet life cycle is managed by the servlet container and consists of the following stages:
- Instantiation: The servlet object is created by the container when it receives the first request for the servlet or during startup (based on configuration).
- Initialization: The container calls the
init()method to initialize the servlet. This is called only once during the servlet's lifetime. - Service: The
service()method is invoked for each client request. It determines the HTTP method (e.g., GET, POST) and calls the appropriate method (e.g.,doGet(),doPost()). - Destruction: The
destroy()method is called when the servlet is being removed from memory, allowing it to release any resources.
Example Code for Servlet Life Cycle
The following example demonstrates all the key methods in the servlet life cycle:
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class LifeCycleExampleServlet extends HttpServlet {
// Called once when the servlet is initialized
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("Servlet is being initialized...");
}
// Handles client requests (called multiple times for each request)
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("<h2>Welcome to the Servlet Life Cycle Example</h2>");
out.println("<p>Servlet is processing the request...</p>");
out.println("");
System.out.println("Processing request...");
}
// Called when the servlet is being destroyed
@Override
public void destroy() {
System.out.println("Servlet is being destroyed...");
}
// Optionally used to get information about the servlet
@Override
public String getServletInfo() {
return "LifeCycleExampleServlet - Demonstrates Servlet Life Cycle";
}
}
Explanation of Methods:
init(ServletConfig config):Initializes the servlet. Called once when the servlet is first loaded.doGet(HttpServletRequest request, HttpServletResponse response):Handles HTTP GET requests. This method processes the client’s requests and generates responses.destroy():Cleans up resources before the servlet is removed from memory.getServletInfo():Provides metadata about the servlet (optional).
When is the Servlet Object Created?
The servlet object is created by the container:
- On first request: If
load-on-startupis not specified, the servlet object is created when the first request is received for the servlet. - At server startup: If
load-on-startupis specified in the web.xml or using annotations, the servlet object is created during server startup.
How many times is the servlet object created? A single servlet object is created per servlet declaration during the web application’s lifetime (singleton pattern). Multiple threads handle concurrent requests to the same servlet instance.
What is Load on Startup?
The load-on-startup element in the web.xml file specifies whether a servlet should be loaded at server startup or on the first request:
- If the value is a positive integer, the servlet will be loaded at server startup. The value determines the loading order (lower values are loaded first).
- If not specified or set to a negative value, the servlet will be loaded lazily on the first request.
Example Configuration in web.xml:
ExampleServlet
com.example.ExampleServlet
1
What is web.xml?
The web.xml file, also known as the deployment descriptor, is an XML file used to configure servlets and other web application settings. It is located in the WEB-INF directory of a Java web application.
Key Configurations in web.xml:
- Servlet declarations and mappings.
- Session configuration.
- Security settings (e.g., authentication, authorization).
- Application context parameters.
Example web.xml:
ExampleServlet
com.example.ExampleServlet
ExampleServlet
/example
@WebServlet Annotation
The @WebServlet annotation is an alternative to configuring servlets in the web.xml file. It is used to declare a servlet and map it to a URL pattern directly in the Java code.
Example Using @WebServlet:
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
@WebServlet(name = "ExampleServlet", urlPatterns = {"/example"})
public class ExampleServlet extends HttpServlet {
// Servlet implementation
}
Benefits of Using @WebServlet:
- Simplifies servlet configuration.
- Eliminates the need for
web.xmlin many cases. - Provides cleaner and more maintainable code.