The life cycle of a servlet is controlled by the servlet engine.
Servlets are instantiated (loaded) and destroyed (unloaded) by the servlet engine.
For a generic servlet, the servlet engine calls the following methods:
init()
when the servlet is first loaded.
service()
when each request is received.
destroy()
just before the servlet is unloaded.
void init()
- Called once when the servlet is first loaded.
- Not called for each request.
- To perform one-time initialization or configuration of the servlet, e. g.
- reading initialization parameters
- reading configuration parameters from
property files or other resources
- setting up databases
- To be overridden by subclasses. No need to call
super.init().
abstract void service(ServletRequest request,
ServletResponse response)
- Called when each request is received.
- To be overridden by subclasses to handle requests.
- Executed in a new thread for each request.
- Multiple threads may execute this method at the same time.
- However, you could choose the single thread model
to prevent multiple threads to execute this method at the same time,
but this is a bit of a problem... why?
void destroy()
- Called just before the servlet is unloaded.
- Not called after each request.
- To release resources.
- Servlets may be unloaded by the servlet container at any time.


