|Servlet Life Cycle|
|A Simple Servlet|
|web.xml Servlet Configuration|
A servlet follows a certain life cycle. The servlet life cycle is managed by the servlet container. The life cycle contains the following steps:
Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it. You can force the container to load the servlet when the container starts up though. See web.xml Servlet Configuration for more details about that.Step 4 is executed multiple times - once for every HTTP request to the servlet.
|The Java Servlet life cycle|
Before a servlet can be invoked the servlet container must first load its class definition. This is done just like any other class is loaded.
When the servlet class is loaded, the servlet container creates an instance of the servlet.
Typically, only a single isntance of the servlet is created, and concurrent requests to the servlet are executed on the same servlet instance. This is really up to the servlet container to decide, though. But typically, there is just one instance.
When a servlet instance is created, its
init() method is invoked. The
init() method allows a servlet to initialize itself before the first
request is processed.
You can specify init parameters to the servlet in the web.xml file. See web.xml Servlet Configuration for more details.
For every request received to the servlet, the servlets
service() method is called.
HttpServlet subclasses, one of the
etc. methods are typically called.
As long as the servlet is active in the servlet container, the
service() method can
be called. Thus, this step in the life cycle can be executed multiple times.
When a servlet is unloaded by the servlet container, its
destroy() method is called.
This step is only executed once, since a servlet is only unloaded once.
A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at runtime.