Middle
What is the lifecycle of servlets and what stages does it include?
sobes.tech AI
Answer from AI
The servlet lifecycle is managed by the servlet container. It goes through the following stages:
- Loading: The container loads the servlet class.
- Instantiation: A single instance of the servlet is created using the
Class.newInstance()method. Servlets are singletons within the application context. - Initialization: The container calls the
init(ServletConfig config)method. This method is called only once during the entire lifecycle of the servlet. It is used for initialization tasks such as reading configuration parameters, establishing database connections, etc.// Example init() method public void init(ServletConfig config) throws ServletException { super.init(config); // Initialize resources System.out.println("Servlet initialized."); } - Request Handling: The servlet is ready to process client requests. For each incoming request, the container creates a new thread and calls the
service(ServletRequest request, ServletResponse response)method. Theservice()method typically delegates request processing to other specific methods such asdoGet(),doPost(),doPut(),doDelete()depending on the HTTP request type.// Example service() method public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Delegate request processing super.service(request, response); } // Example doGet() method protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1>Hello from the servlet!</h1>"); } - Destruction: When the container decides to unload the servlet (for example, when stopping the application), it calls the
destroy()method. This method is called only once before the servlet instance is destroyed. It is used for releasing resources such as closing database connections, clearing caches, etc.// Example destroy() method public void destroy() { // Release resources System.out.println("Servlet destroyed."); }
In summary, the stages can be represented in a table:
| Stage | Method called by container | Description | Called once |
|---|---|---|---|
| Class loading | - | The servlet class is loaded into memory | Once |
| Instance creation | Class.newInstance() |
An instance of the servlet is created | Once |
| Initialization | init(ServletConfig config) |
Performs initialization tasks | Once |
| Request processing | service(...), doGet(...), doPost(...), etc. |
Handles incoming client requests | Multiple times |
| Destruction | destroy() |
Releases resources before the servlet instance is removed | Once |