Article From:https://segmentfault.com/q/1010000011713203
Question:

Servlet filter, please.
Is every request made by Tomcat new an instance?
Or is it shared globally?

Answer 0:

In the Servlet specification, the definitions of Servlet singleton and multiple cases are as follows:

“Deployment Descriptor”, controls how the servlet container provides instances of the servlet.For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.

Mentioned above,
If a servlet is not deployed in a distributed environment, a servlet declared in Web.Xml generally corresponds to only one instance.

If a Servlet implements the SingleThreadModel interface, multiple instances will be initialized. How many examples are there?

The Servlet that implements the SingleThreadModel interface, how many instances will be initialized?
StandardWrapperThere are two properties in the class, where maxInstance is initially 20. So the answers to the above questions are answered.

/**
 * Does this servlet implement the SingleThreadModel interface?
 */
protected volatile boolean singleThreadModel = false;
/**
 * Maximum number of STM instances.
 */

protected int maxInstances = 20;

As SingleThreadModel has been declared obsolete, it is not recommended by the government. We are just letting you know.

To sum up, how many instances does a Servlet have? Affected by the following reasons:
Deployment in distributed environment
If SingleThreadModel is implemented, 20 instances will be created if it is implemented.
Declare several times in Web.Xml, and even if the same servlet is declared multiple times, multiple instances will be generated.

Answer 1:

Each request will create a servlet instance and a filter instance:
The life cycle of the two is as follows:

filter:init()---Start serviceServlet:init ()Filter:service () - RequestServlet:service ()Servlet:destroy ()Filter:destroy () - closingservice

Answer 2:

The Servlet object is created only when the Servlet is first requested, and then the Servlet is created before each request to the Servlet is used and will not be recreated

Link of this Article: Servlet filter problem

Leave a Reply

Your email address will not be published. Required fields are marked *