Servlet lifecycle

1、 Architecture diagram

Servlet execution process:

Step 1: the HTTP request is delegated to the servlet container by the server

Step 2: load Servlet

Step 3: the servlet container handles multiple requests generated by multiple threads, and each thread executes the service () method of a single servlet instance

2、 Methods in servlet:

1、init()

The init method is designed to be called only once. It is called the first time the servlet is created and will not be called every subsequent user request. Therefore, it is used for one-time initialization.

The servlet is created when the user first calls the URL corresponding to the servlet, but you can also specify that the servlet is loaded when the server starts for the first time.

When a user calls a servlet, a servlet instance will be created. A new thread will be generated for each user request and handed over to the doget or dopost method when appropriate. The init () method simply creates or loads some data that will be used throughout the life cycle of the servlet.

2、servic()

The service () method is the main method for performing actual tasks. The servlet container (that is, the web server) calls the service () method to process the request from the client (browser), and writes the formatted response back to the client.

Each time the server receives a servlet request, the server will generate a new thread and call the service. The service () method checks the HTTP request type (get, post, put, delete, etc.) and calls doget, dopost, doput, dodelete, etc. when appropriate.

3、destroy()

The destroy () method is called only once, at the end of the servlet life cycle. The destroy () method allows your servlet to close database connections, stop background threads, write cookie lists or click counters to disk, and perform other similar cleanup activities. After the destroy () method is called, the servlet object is marked as garbage collected.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>