The servlet is run in a servlet container and its lifecycle is managed by the container. The life cycle of the servlet is represented by the Init (), Servce (), and Destory () methods in the Javax.servlet.Servlet interface.
1, loading and instantiation
The servlet container is responsible for loading and instantiating the servlet when the container starts or detects in the container that the servlet is needed to respond to a request. Creates a servlet instance. The container uses the Java Reflection API to create a servlet instance. Therefore, constructors with parameters should not be provided in the servlet.
2, Initialize
After the servlet is instantiated, the container must call the init () method to initialize the object. The purpose of initialization is to have the Servlet object do some initial work before processing the client request. For each servlet instance, the init () method is called only once.
3, request processing
The servlet container invokes the service () method on the request processing. The servlet instance obtains information about the client and requests information through the ServletRequest object. Sets the response information when the Servletresponse object is called after processing the request.
4, termination of service
When the container detects that a servlet instance should be removed from the server, the container invokes the instance's Destory method. Let the instance release the resources it occupies. A new servlet instance is created if the request is made at a time.
During the lifetime of the servlet, the servlet instance is created, the init () and Destory () methods of the calling instance are executed only once, and when the initial session is complete, the servlet container holds the instance in memory and the Servlce () method is used to accept the request service.
Deep understanding of servlet operating mechanism and life cycle