Middle
How does a servlet container manage the servlet lifecycle? When and which methods are called?
sobes.tech AI
Answer from AI
The servlet container manages the servlet's lifecycle by calling its methods at specific moments:
- Loading the servlet class: The container loads the servlet class upon the first request or at server startup (if preloading is configured).
- Creating a servlet instance: The container creates an instance of the servlet class using the no-argument constructor.
- Initializing the servlet: The container calls the
init(ServletConfig config)method. This method is called only once during the servlet's lifecycle.// Servlet initialization method public void init(ServletConfig config) throws ServletException { super.init(config); // Initialization of resources, configuration, etc. } - Handling requests: For each incoming request, the container calls the
service(ServletRequest req, ServletResponse res)method. This method determines the request type (GET, POST, etc.) and calls the correspondingdoGet(),doPost(), etc. In HttpServlet, theservicemethod is implemented by default and usually does not need to be overridden.// Handling requests public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // Forwarding request to doGet, doPost, etc. in HttpServlet } // Handling GET requests protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Logic for handling GET request } // Handling POST requests protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Logic for handling POST request } - Destroying the servlet: The container calls the
destroy()method before unloading the servlet from memory. This occurs when the container is stopped or when resources need to be released. Thedestroy()method is also called only once.// Servlet destruction method public void destroy() { // Resource cleanup (closing connections, files, etc.) super.destroy(); }
| Method | When called | Number of calls |
|---|---|---|
init() |
On the first request to the servlet or at server start | Once |
service() |
For each incoming request | Multiple times |
doGet(), etc. |
For each specific request type | Multiple times |
destroy() |
Before removing the servlet from memory | Once |