Life cycle of a servlet from the perspective of the container
- After start, the container is looking for servlet classes in the appropriate directory (for Apache Tomcat it would be
$TOMCAT_HOME/webapps). - Once they are found, there are two possible ways: servlets are loaded immediately or only when someone wants to use them. By using the term “load servlet” I mean the execution of its constructor and init() method. init() is executed only once in the life cycle of a servlet. It allows you to prepare it for usage (e.g. to connect to the database, initialize any resources).
The code below presents a fragment of the web.xml file allowing to define the order in which servlets are loaded when the container starts:
<web-app>
...
<servlet>
<servlet-name>FirstToLoadServlet</servlet-name>
<servlet-class>pl.tdziurko.scwcd.servlets.FirstToLoadServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>SecondToLoadServlet</servlet-name>
<servlet-class>pl.tdziurko.scwcd.servlets.SecondToLoadServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
</web-app>
Regarding the load-on-startup element, the specification states that:
- The value of the element must be an integer
- Servlets are loaded starting from the one with number 0
- For values lower than 0 the container can load the servlet at any time, the same behaviour exists when there is no load-on-startup element in the web.xml
- For servlets with the same value of the load-on-startup element, the container can load them in any order
But back to our life cycle:
- Execution of service() method for incoming requests.
- Execution of destroy() method which allows the servlet to release its resources. This method is executed only once in the whole life cycle.
Life cycle of a servlet from the user’s perspective
- User enters url matching servlet class.
- Container seeing that the address refers to the servlet, creates two objects implementing interfaces HttpServletRequest and HttpServletResponse, then finds appropriate servlet (defined in web.xml), creates a new thread and calls service() method passing request and response objects as arguments.
- Method service() calls doXXX() method on the basis of the type of HTTP method. Most often it’s doGet() or doPost(). Same arguments (req, resp) are passed to this method.
- Called method generates response and writes it to the received HttpServletResponse object.
- service() method ends, response is sent to the user, thread dies (or returns to the pool). Cycle ends.