Servlet Tutorial
A Servlet is managed through a life cycle that defines how it is loaded and initialized, handles requests from clients, and is taken out of service. This life cycle is managed by the container in which the servlet runs.
The servlet lifecycle mainly includes three methods: init(), service(), and destroy().
Let's discuss these methods in detail:
init() method: This method is called by the servlet container to indicate to a servlet that the servlet is being placed into service. The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
service() method: The service method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
destroy() method: This method is called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the service method have exited or after a timeout period has passed.
Here's a simple servlet code that demonstrates the servlet life cycle:
package com.example; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/LifecycleServlet") public class LifecycleServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init() throws ServletException { System.out.println("Servlet is being initialized"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet is servicing a GET request"); response.getWriter().println("<h1>Servlet LifeCycle Example</h1>"); } public void destroy() { System.out.println("Servlet is being destroyed"); } }
In this servlet, we're overriding the init() and destroy() methods to print a message when they're called. The doGet() method prints a message whenever a GET request is handled. If you run this servlet and send a GET request to it, you'll see the messages printed in your server's console.
Remember, a servlet instance can handle multiple requests throughout its lifetime, so the init() method is called once (when the servlet is first loaded), and the destroy() method is called once (when the servlet is unloaded). The service-related methods (like doGet(), doPost(), etc.) are called for each client request.
Servlet init() method and initialization:
The init()
method is called when a Servlet is first created. It is used for one-time initialization.
public void init(ServletConfig config) throws ServletException { // Initialization code }
Java Servlet service() method:
The service()
method handles the actual processing of requests. It is called for each request.
doGet()
, doPost()
, etc., based on the request method.public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Request handling code }
Servlet doGet() and doPost() methods:
Specific HTTP method handling methods. doGet()
for GET requests, doPost()
for POST requests.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handling GET requests } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handling POST requests }
Destroying a Servlet in Java:
The destroy()
method is called when a Servlet is being taken out of service.
public void destroy() { // Cleanup code }
Servlet context and config in life cycle: Access Servlet context and config information during the life cycle.
ServletConfig config = getServletConfig(); ServletContext context = getServletContext();
Handling session-related tasks in Servlet life cycle:
Manage sessions using HttpSession
for user-related data across requests.
HttpSession session = request.getSession();
Java Servlet init parameters: Configure Servlets with initialization parameters.
web.xml
or use annotations.String paramValue = getInitParameter("parameterName");