Servlet life cycle
The servlet life cycle can be defined throughout the process from creation to destruction.
(1) The servlet invokes the Init () method to initialize
(2) Servlet calls the service () method to handle client requests
(3) Servlet terminated by Destroy () method
(4) Finally, the servlet is recycled by the JVM's garbage collector
Init () method
The init () method is designed to be called only once. Called only the first time the servlet is created, and is no longer invoked each time a user requests it.
The servlet is created when the user first invokes the URL for the servlet, but can also specify that the servlet is loaded the first time the server is started.
When a user invokes a servlet, a servlet instance is created, and each user request generates a new thread that is handed over to the doget () or Dopost () method when appropriate. The init () method simply creates or loads some data that will be used for the entire life cycle of the servlet.
The init () method is as follows:
public void Init () throws servletexception{
Initialize code ...
}
Service () method
The service () method is the primary way to perform the actual task. The servlet container (Web server) invokes the service () method to process the client request and returns the formatted response to the client.
Each time the server receives a servlet request, it generates a new thread and invokes the service. The service () method examines the HTTP request type (Get/post/put/delete, etc.) and calls methods such as doget ().
Here is the method:
public void Service (ServletRequest request,servletresponse response) throws servletexception,ioexception{
Code
}
Doget () method
A GET request comes from a normal request for a URL, or from an HTML form that does not specify a method, which is handled by the Doget () method.
public void Doget () throws servletexception,ioexception{
Code
}
DoPost () method
The POST request comes from a specified method as an HTML form, which is chuli by the Dopost () method.
public void DoPost (HttpServletRequest request,httpservletresponse response) throws servletexception,ioexception{
Code
}
Destroy () method
The Destroy () method is called only once and is called at the end of the servlet's life cycle. The Destroy () method allows the servlet to close the database connection, stop the background thread, and write the cookie list or hit counter to disk.
After destroy () is called, the Servlet object is marked as garbage collection.
public void Destroy () {
Termination code
}
Second, servlet-life cycle