How tomcat works Reading Notes 11 StandWrapper

Source: Internet
Author: User

How tomcat works Reading Notes 11 StandWrapper
Method Call Sequence

Shows the collaboration diagram of method calls:


This is the figure I drew in Chapter 5 above:

Let's look back at the connector
Connector. getContainer (). invoke (request, response );
What happens after this code is run;
This is the sequence diagram of chapter 5, which is also applicable in this chapter...
Let's take a closer look:
1. First, the connector creates a request and response object;
2. Call this line of code
Connector. getContainer (). invoke (request, response)
(We use StandContext as the top-layer container)
3. In the container, the invoke method of StandardPipeline is called first. As follows:
   public void invoke(Request request, Response response)        throws IOException, ServletException {        // Invoke the first Valve in this pipeline for this request        (new StandardPipelineValveContext()).invokeNext(request, response);    }
4StandardPipeline has an internal class StandardPipelineValveContext. Its invokeNext method loops all valves in the pipeline (the pipeline of StandardContext) until the base valve and calls its invoke method. The StandardContextValve () is specified by default when StandardContext is initialized ();
5. Call the map method of StandardContext to obtain Wrapper through the invoke method of the base valve.
6. The invoke method of the wrapper (StandardWrapper) obtained by calling...
7. Repeat Step 3 and Step 4. The basic valve is StandardWrapperValve. Its invoke method is to call the allocate method of the StandardWrapper class, and allocate calls loadServlet to obtain the servlet.
8. Generate a request (servlet) in ApplicationFilterChain: createFilterChain, and then call the servlet service method in its internalDoFilter method.

The SingleThreadModel interface ensures that only one process accesses a serlvet service method at any time within the container.
This interface is an empty interface or a flag interface. There is nothing inside it. It is just a sign.
A servlet that implements this interface is commonly called a program component of SingleThreadModel (STM.
Many Programmers think that as long as the above interfaces are implemented, their servlets can be thread-safe.
Otherwise, what if several servlet service methods access a static class variable or a class or variable other than the servelt class?
Therefore, this interface has been discarded in Servlet 2.4 because it gives programmers a false sense of security.

The main function of StandardWrapperStandardWrapper is to load the servlet class it represents and instantiate it. However, by analyzing the Call Sequence diagram above, we know that it is to call its own pipeline first, the base valve then calls the alloacte method of StandardWrapper.
As mentioned above, there is an STM. If the container only maintains a servelt that implements the STM interface, it should be called like this.
    Servlet instance = 
 
  ;    if ((servlet implementing SingleThreadModel>) {        synchronized (instance) {            instance.service(request, response);        }    }    else {        instance.service(request, response);    }
 
To maintain performance, StandardWrapper generally maintains an STM servlet instance pool.
A package is also responsible for preparing an instance of javax. servlet. ServletConfig.
The servlet is complete internally. The next two sections will discuss how to allocate and load the servlet.


Alloacte method this method can be divided into two parts:
First, non-producer servlet is generated.
StandardWrapper defines a java. servlet. Servlet instance.
Private Servlet instance = null;
The allocate method checks whether the instance is null. If the loadServlet method is called to load the servlet. Add the contAllocated integer and return the instance.

Second, the producer servlet is generated.
Method allocate tries to return an instance in the pool. The variable intancePool is a java. util. Stack-type STM servlet instance pool.
Here I want to explain three variables:
CountAllocated: number of currently active servelt
The count of allocations that are currently active (even if they are for the same instance, as will be true on a non-STM servlet ).
NInstances: Number of loaded serlvet
Number of instances currently loaded for a STM servlet.
MaxInstances: the maximum number of servlets supported by StandardWrapper.
The above three variables will surely make everyone dizzy, but I want to say that a StandardWrapper maintains a servlet with only one class address, the three variables are used for multithreading!
This part of the code is quite troublesome, both in understanding and speaking.
All in all, at the beginning, countAllocated and nInstances were both 0. loadServlet () First generates a servelt, pushes it to the servlet instance pool, and then retrieves it ..
You can read the code by yourself (I think I am a little lazy)

LoadServlet method this method will first check the instance. If it is not null and the current StandardWrapper does not represent an ingress servlet class, it will be returned directly.
On the other hand, Catalina is also a jsp Container. If the requested servelt is a jsp, execute the following code segment:
String actualClass = servletClass;
If (actualClass = null) & (jspFile! = Null )){
Wrapper jspWrapper = (Wrapper) (Context) getParent (). findChild (Constants. JSP_SERVLET_NAME );
If (jspWrapper! = Null)
ActualClass = jspWrapper. getServletClass ();
}
The following shows how to obtain the classloader. By default, we can see the content in the previous chapters. In Bootstrap, we have already specified WebappLoader. Through this, we can obtain the WebappClassLoader object.
However, in tomcat, if the servlet to be loaded is located under org. apache. catalina., The classLoader is
ClassLoader = this. getClass (). getClassLoader (); // this is StandardWrapper
The next step is loadClass, and then the servlet is obtained using the newInstance of the Class;
Check whether the servlet is allowed to be loaded (I am not very familiar with this step) and whether it implements the ContainerServlet interface.
The ContainerServlet Interface contains the set/getWrapper method, which allows the servlet to access the internal functions of Catalina.
The following describes how to call servlet. init (facade). This facade is an appearance variable of javax. servlet. ServletConfig.
If the StandardWrapper object represents an STM Servlet, add the instance to the instance pool. Therefore, if the instance pool is null, create it first.
// Register our newly initialized instance
SingleThreadModel = servlet instanceof SingleThreadModel;
If (singleThreadModel ){
If (instancePool = null)
InstancePool = new Stack ();
}
FireContainerEvent ("load", this );
}
Finally, the servlet is returned.


The parameter of the servlet init method above the ServletConfig object is actually an instance of the javax. servlet. ServletConfig interface.
The problem arises. Where does the instance of this interface come from? Let's take a look at the Declaration part of StandardWrapper and we will know that it implements the ServletConfig interface.
However, when calling the init method, StandardWrapper does not directly pass itself over but uses a facade. Why do I directly pass StandardWrapper over, are all public methods in StandardWrapper exposed?
The ServletConfig interface has the following four methods: getServletContext, getServletName, getInitParameter, and getInitParameterNames.

1 getServletContext
Public ServletContext getServletContext (){
If (parent = null)
Return (null );
Else if (! (Parent instanceof Context ))
Return (null );
Else
Return (Context) parent). getServletContext ());
}
Now you know that you cannot deploy a package separately to represent a Servlet. The package must belong to a context container so that you can use the ServletConfig object to get a ServletContext instance using the getServletContext method.

2 getServletName
Get the servlet name. Nothing to say

3 getInitParameter
Obtain the value of the specified initial parameter. The initial parameters in StandardWrapper are placed in a HashMap:
Private HashMap Parameters = new HashMap ();
The specific implementation is very simple.

4 getInitParameterNames
The returned result is a set of initialization parameter names, which is an enumeration class.

The StandardWrapperFacade class diagram is as follows:
There are four methods in ServletConfig: getServletName, getInitParameter, and getInitParameterNames of the facade class call StandardWrapper directly. These are simple and there is nothing to say.
However, getServletContext is a bit complicated:
Public ServletContext getServletContext (){
ServletContext theContext = config. getServletContext ();
If (theContext! = Null )&&
(TheContext instanceof ApplicationContext ))
TheContext = (ApplicationContext) theContext). getFacade ();
Return (theContext );
}
As you can see, call StandardWrapper to obtain the Context, but the Facade is returned to the outside. (Real tm is complex ).

The following chapters will be discussed.
StandardWrapperValve, FilterDef, ApplicationFilterConfig, ApplicationFilterChain

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.