Introduction to the life cycle and working principle of Servlet

1、 Servlet lifecycle

The servlet life cycle is divided into three stages:

1) initialization phase: call init() method

2) response to customer requests: call the service () method

3) termination phase: call destroy() method

Workflow of Tomcat and servlet:

Steps:

1. Servlet initialization phase:

The servlet container loads servlets at the following times:

1) when the servlet container starts, some servlets are loaded automatically, and it only needs to be implemented on the web Add the following code between < servlet > < / servlet > in the XML file:

2) after the servlet container is started, the customer sends a request to the servlet for the first time

3) after the servlet class file is updated, reload the servlet

After the servlet is loaded, the servlet container creates a servlet instance and calls the init () method of the servlet for initialization. The init () method is called only once throughout the life cycle of the servlet.

2. Servlet response request stage:

For the user's request to reach Servlet, the Servlet container creates the ServletRequest object and ServletResponse object specific to the request, and then calls the service method of Servlet. The service method obtains the customer request information from the ServletRequest object, processes the request, and returns the response information to the customer through the servletresponse object.

For tomcat, it will put the passed parameters in a hashtable. The definition of the hashtable is:

This is a key value mapping of string -- > string [].

HashMap thread is not safe, and hashtable thread is safe.

3. Servlet termination phase:

When the web application is terminated, the servlet container terminates, or the servlet container reloads a new instance of the servlet, the servlet container will first call the destroy () method of the servlet, in which the resources occupied by the servlet can be released.

2、 How servlets work

1, first, simply explain the process of Servlet receiving and responding to customer requests. First, the customer sends a request. Servlet calls the service () method to respond to the request. Through the source code, service () method matches the way of request, calls doGet, doPost and other methods, then enters the corresponding method to call the logical layer method. Achieve customer response. There are no doget, dopost and other methods in the servlet interface and genericservlet. These methods are defined in httpservlet, but they all return error information. Therefore, each time we define a servlet, we must implement doget, dopost and other methods.

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
分享
二维码
< <上一篇
下一篇>>