1. Let’s start with the servlet container: The servlet container that everyone is most familiar with is Tomcat. How does servlet container manage servlets?
Let’s take a look at the container model of tomcat first:
From the above figure, we can see that Tomcat's container is divided into four levels. The container that truly manages Servlets is the Context container, and a Context corresponds to a Web project
In Tomcat's container level, 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 how the Servlet works.
Here I will explain the wrapping class of servlet: StandardWrapper. There is a question here, why should Servlet be wrapped into StandardWrapper instead of being a Servlet object directly. Because StandardWrapper is part of the Tomcat container, it has the characteristics of the container, and Servlet is an independent web development standard and should not be strongly coupled in Tomcat.
Except for wrapping the servlet into StandardWrapper and adding it to the Context as a subcontainer, all other web.xml properties are parsed into the Context, so the Context container is the Servlet container that really runs the servlet. A web application corresponds to a Context container. The configuration properties of the container are specified by the application's web.xml, so we can understand what role web.xml plays.
2. The following briefly describes the working project of servlet:
When a web server interacts with the client, the working process of Servlet is:
1. Make a request to the web server on the client
2. The web server sends it to the Servlet after receiving the request
3. The Servlet container generates an instance object for this and calls the corresponding method in the Servlet API to process the client HTTP request, and then returns the processed response result to the WEB server.
4. The web server sends the response structure received from the Servlet instance object back to the client.
3. The life cycle of servlet:
As shown in the figure above, the life cycle of a servlet can be divided into four stages, namely the loading class and the creation stage, the initialization stage, the service stage and the instance destruction stage. The following is a detailed description of the programming tasks and precautions for each stage.
1. Create a servlet instance:
By default, Servlet instances are created when the first request arrives and are reused later. If some servlets require complex operations that need to be completed when loading initialization, such as opening files, initializing network connections, etc., you can notify the server to create an instance of the servlet when starting. The specific configuration is as follows:
<servlet><servlet-name>TimeServlet</servlet-name><servlet-class>com.allanlxf.servlet.basic.TimeServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>
Create the relevant class structure of the 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 the initialization parameter, which is created by the server.
I. How to configure the initialization parameters of Servlet?
In the definition tag of the Servlet in web.xml, for example:
<servlet><servlet-name>TimeServlet</servlet-name><servlet-class>com.allanlxf.servlet.basic.TimeServlet</servlet-class><init-param><param-name>user</param-name><param-value>username</param-value></init-param><init-param><param-name>blog</param-name><param-value>http://. . . </param-value></init-param></servlet>
The two initialization parameters user and blog are configured with the values of username and http://. . . , in this way, in order to modify the username and blog address in the future, you do not need to modify the Servlet code, just modify the configuration file.
II. How to read the initialization parameters of a servlet?
ServletConfig defines the following method to read the information of initialization parameters:
public String getInitParameter(String name)
Parameter: The name of the initialization parameter.
Returns: The value of the initialization parameter, if not configured, returns null.
Number of execution times of III.init(ServletConfig) method
This method is executed once during the life cycle of a servlet.
IV.init(ServletConfig) method and thread
This method is executed in a single threaded environment, so developers do not need to consider thread safety issues.
V.init(ServletConfig) method and exception
During execution, this method can throw a ServletException to notify the web server that the Servlet instance has failed to initialize. Once a ServletException is thrown, the web server will not hand over the client request to the Servlet instance for processing, but will report the initialization failure exception information to the client, which will be destroyed from memory. If a new request is made, the web server will create a new Servlet instance and perform the initialization operation 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. During the service stage, the web server will call the service (ServletRequest request, ServletResponse response) method of the instance. The request object and the 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.
I. Responsibilities of the service() method
The service() method is the core method of the Servlet. The client's business logic should be executed within this method. The development process of a typical service method is:
Analyze 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 developers must ensure the thread safety of the method.
III.service() method and exception
The service() method can throw ServletException and IOException during execution. Among them, ServletException can be thrown during the process of processing client requests, such as the requested resource is unavailable, the database is unavailable, etc. Once the exception is thrown, the container must recycle the request object and report the client's exception information. IOException indicates an input and output error. The programmer does not have to care about the exception and reports it directly to the client by the container.
Programming precautions:
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 the client, the server will execute the service() method of the Servlet instance in a separate Client Service Thread 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 issues 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. Instead, it depends on the type of resource accessed by this method during execution and how it accesses resources. The analysis is as follows:
i. If the service() method does not access the Servlet 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, requests and response objects that do not point to the global resources. This method itself is thread-safe and does not require any synchronization control.
ii. If the service() method accesses the Servlet member variable, but the operation on the variable is a read-only operation, the method itself is thread-safe and does not require any synchronization control.
iii. If the service() method accesses the Servlet member variable and the operation of the variable is read and written, a synchronization control statement is usually required.
iv. If the service() method accesses a global static variable, if there may be other threads in the system accessing the static variable at the same time, if there are both read and write operations, a synchronization control statement is usually required.
v. If the service() method accesses global resources, such as files, database connections, etc., it is usually necessary to add synchronization control statements.
4. Destruction
When the web server thinks that the Servlet instance is not necessary, such as application reloading, or server shutdown, and the Servlet has not been accessed for a long time. The server can destroy (also called uninstalling) the instance from memory. The web server must ensure that the destroy() method of the Servlet instance is called before uninstalling the Servlet instance, in order to recycle the resources requested by the Servlet or perform other important processing.
The web server must ensure that before calling destroy() method, all threads running in the service() method of the instance exit or wait for these threads for a period of time. 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. Flowchart of servlet parsing client http request:
1. The web client issues an HTTP request to the Servlet container;
2. The Servlet container parses the web HTTP request.
3. The Servlet container creates an HttpRequest object, encapsulating the http request information in this object;
4. The Servlet container creates an HttpResponse object;
5. Servlet container (if the accessed servlet is not created at the server startup, first create a servlet instance and call the init() method to initialize the object) call the service() method of the HttpServlet, and pass the parameters of the HttpRequest and HttpResponse objects as service methods to the HttpServlet object;
6. HttpServlet calls the relevant methods of HttpRequest to obtain HTTP request information;
7. HttpServlet calls the relevant methods of HttpResponse to generate response data;
8. The Servlet container passes the HttpServlet response result to the web client.
The above article is based on servlet's execution principle and life cycle (comprehensive analysis) is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.