Servlet based execution principle and life cycle (comprehensive analysis)
1、 Let's start with the servlet container: the most familiar servlet container is Tomcat. How does the servlet container manage servlets?
Let's take a look at the container model of Tomcat:
As can be seen from the above figure, Tomcat's containers are divided into four levels. The container that really manages servlets is the context container, and a context corresponds to a web project
In the container level of tomcat, the context container is a container that directly manages the wrapper class wrapper (standardwrapper) of the servlet in the container, so how the context container runs will directly affect the working mode of the servlet.
Let's explain the wrapper class of servlet: standardwrapper. Here's a question: why should a servlet be wrapped as a standardwrapper instead of a servlet object. Because standardwrapper is a part of Tomcat container, it has the characteristics of container. Servlet is an independent web development standard and should not be strongly coupled in Tomcat.
In addition to wrapping the servlet as a standardwrapper and adding it to the context as a sub container, all other web XML attributes are parsed into context, so the context container is the servlet container that really runs servlets. A web application corresponds to a context container, and the configuration properties of the container are determined by the web XML, so that we can understand the web What exactly does xml do
2、 The following is a brief description of the servlet work project:
When the web server interacts with the client The working process of servlet is:
1. Send a request to the web server at the client
2. After receiving the request, the web server sends it to the servlet
3. The servlet container generates an instance object for this purpose, calls the corresponding methods in the servlet API to process the client HTTP request, and then returns the processed response results to the web server
4. The web server sends the response structure received from the servlet instance object back to the client
3、 Servlet lifecycle:
As shown in the figure above, the life cycle of a servlet can be divided into four stages: loading classes and creating instances, initialization, service, and instance destruction. The following describes the programming tasks and precautions of each stage in detail.
1. Create servlet instance:
By default, servlet instances are created when the first request arrives and reused later. If some servlets require complex operations that need to be completed during initialization, such as opening files and initializing network connections, you can notify the server to create an instance of the servlet at startup. The specific configuration is as follows:
Create relevant class structure of servlet object:
2. Initialization
Once the servlet instance is created, the web server will automatically call the init (ServletConfig config) method to initialize the servlet. The method parameter config contains the configuration information of the servlet, such as initialization parameters. This object is created by the server.
1. How to configure the initialization parameters of a servlet?
On the web The servlet definition tag in XML, for example:
Two initialization parameters user and blog are configured. Their values are username and http: / /..., In this way, if you want to modify the user name and blog address in the future, you don't need to modify the servlet code, just modify the configuration file.
II. How to read the initialization parameters of a servlet?
The following methods are defined in ServletConfig to read the information of initialization parameters:
public String getInitParameter(String name)
Parameter: the name of the initialization parameter.
Return: the value of the initialization parameter. If it is not configured, null is returned.
3. Number of init (ServletConfig) method executions
This method is executed once in the life cycle of the servlet.
4. Init (ServletConfig) method and thread
This method is executed in a single threaded environment, so developers do not need to consider thread safety.
5. Init (ServletConfig) method and exception
This method can throw a ServletException during execution to notify the web server that the servlet instance initialization fails. Once the servlet exception is thrown, the web server will not give the client request to the servlet instance for processing, but report the initialization failure exception information to the client, and the servlet instance will be destroyed from memory. If a new request comes, the web server will create a new servlet instance and perform the initialization of the new instance
3. Service
Once the servlet instance is successfully created and initialized, the servlet instance can be used by the server to serve the client's request and generate a response. In the service phase, the web server will call the service (ServletRequest, servletresponse, response) method of the instance. The request object and response object are created by the server and passed to the servlet instance. The request object encapsulates the information sent by the client to the server, and the response object encapsulates the information sent by the server to the client.
1. Responsibilities of the service () method
The service () method is the core method of servlet. The business logic of the client should be executed in this method. The development process of typical service methods is as follows:
Parse client request - > execute business logic - > output response page to client
II. Service () method and thread
In order to improve efficiency, the servlet specification requires that a servlet instance must be able to serve multiple client requests at the same time, that is, the service () method runs in a multi-threaded environment, and the servlet developer must ensure the thread safety of this method.
3. Service() method and exception
The service () method can throw ServletException and IOException during execution. ServletException can be thrown in the process of processing client requests, such as the requested resources are unavailable, the database is unavailable, etc. Once the exception is thrown, the container must recycle the request object and report the exception information to the client. IOException indicates an input / output error. Programmers don't have to care about the exception. They can report it directly to the client by the container.
Notes to programming:
1) When the server thread thread executes the init () method of the servlet instance, all client service thread threads cannot execute the service () method of the instance, and no thread can execute the destroy () method of the instance. Therefore, the init () method of the servlet works in a single thread environment, and developers do not have to consider any thread safety issues.
2) When the server receives multiple requests from clients, the server will execute the service () method of the servlet instance in a separate client service thread to serve each client. At this time, multiple threads will execute the service () method of the same servlet instance at the same time, so thread safety must be considered.
3) Please note that although the service () method runs in a multi-threaded environment, it is not necessary to synchronize the method. It depends on the resource type and access method of the method during execution. The analysis is as follows:
i. If the service () method does not access the servlet's member variables or global resources, such as static variables, files, database connections, etc., it only uses the current thread's own resources, such as temporary variables that do not point to global resources, request and response objects, etc. The method itself is thread safe and does not need any synchronization control.
ii. If the service () method accesses the member variable of the servlet, but the operation on the variable is read-only, the method itself is thread safe and does not need any synchronization control.
III. If the service () method accesses the member variable of the servlet, and there are both read and write operations on the variable, it is usually necessary to add a synchronization control statement.
IV. if the service () method accesses a global static variable, if other threads in the system may access the static variable at the same time, if there are both read and write operations, it is usually necessary to add a synchronization control statement.
v. If the service () method accesses global resources, such as files and database connections, it is usually necessary to add synchronization control statements.
4. Destroy
When the web server thinks that the servlet instance is unnecessary, such as application reloading or server shutdown, and the servlet has not been accessed for a long time. The server can be destroyed from memory (also called unloading). The Web server must ensure that the instance's destroy () method is invoked before unloading the Servlet instance, so that the resources of Servlet application can be recovered or other important processes can be processed.
The web server must ensure that all threads running in the service () method of the instance exit or wait for these threads for a period of time before calling the destroy () method. Once the destroy () method has been executed, the web server will reject all new requests for the servlet instance. The destroy () method exits and the servlet instance can be garbage collected.
4、 Servlet parsing client HTTP request flowchart:
1. The web client sends an HTTP request to the servlet container;
2. The servlet container parses the HTTP request of the web
3. The servlet container creates an httprequest object, which encapsulates the HTTP request information;
4. The servlet container creates an httpresponse object;
5. The servlet container (if the accessed servlet is not created when the server starts, create a servlet instance and call the init () method to initialize the object) calls the service () method of httpservlet, and passes the httprequest and httpresponse objects as parameters of the service method to the httpservlet object;
6. Httpservlet calls relevant methods of httprequest to obtain HTTP request information;
7. Httpservlet calls relevant methods of httpresponse to generate response data;
8. The servlet container transmits the response result of httpservlet to the web client
The above servlet based implementation principle and life cycle (comprehensive analysis) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.