Servlet life cycle summary

The life cycle of a servlet starts from the servlet class loading, to the creation of the servlet class instance, the initialization of the servlet (really becoming a servlet), the arrival of a request, the calling of the service method (main work), until the servlet is destroyed;

1. Servlet class loading:

1.1 After starting the web container, the container searches for the deployment description file (web.xml) of the application, reads the context initialization parameters from the deployment description file, and creates a ServletContext object at this time, and all parts of the application share this context;

1.2 The container creates a String name-value pair for the context-param (parameter name and parameter value are both String types);

1.3 The container passes the name-value pair to the ServletContext object;

1.4 If there is a Listener tag in the deployment description file, create a Listener instance;

1.5 The container calls the contextInitialized method of the Listener and passes in the ServletContextEvent object, which contains a ServletContext reference, and the event processing code can get the context initialization parameters.

 

2. Create an instance of the Servlet class:

2.1 The container reads the Servlet tag in the deployment description file, including initialization parameters (init-param);

2.2 The container creates a ServletConfig instance;

2.3 The container creates name-value pairs for the servlet initialization parameters;

2.4 The container fills ServletConfig with name-value pairs;

2.5 The container creates a new instance of the Servlet class (usually when the first request arrives, or it can be created when the container starts by setting the load-on-start parameter).

 

3. Servlet initialization:

The init method of the servlet is executed only once in a life cycle. Before calling the service method, the initialization must be completed;

There are two init methods in GenericServlet. The init method with parameters calls the init method without parameters. Therefore, if you need to rewrite the init method, you only need to rewrite the init method without parameters.

 

4. Servlet's service method:

Every time a request comes, the service method is called. In HttpServlet, the service method is used to judge the method of the request (without overriding), and to override the doGet method or the doPost method.

    

5. Servlet's destroy method:

Called when the servlet instance is destroyed, which means that the life cycle of the servlet ends.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325298625&siteId=291194637
Recommended