Tomcat Source Code Learning Part 4 – Servlet Request Analysis

Time:2022-11-25

I was busy at home some time ago, and I stopped updating for a long time. I would like to say sorry to the friends who are waiting for the update. I couldn’t explain it in advance. I am really sorry to make you wait for so long!

It’s overTomcatThe initialization and startup steps, then the next step is to enter the highlight! In this article, as before, I will lead my friends to understand aServlethow wastomcatWhat are the specific processing links?

1. Request analysis

The description of each component is noted in “Tomcat Source Code Learning Part 2”.

when aservletWhen a request comes, the first thing that goes through isconnectorComponent, which is used to receive requests.

After the component receives the request, it will encapsulate the relevant request and then pass it toenginein the component.

follow closely,engineComponents will lock the correspondinghostcontextas well aswrapper, passed down layer by layer to find the servlet instance that finally processes the request.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

2. In-depth exploration

I don’t know if you still have any impression. In the previous article, weNioEndpointclass, startAccepterThere is also a thread group running above the entrance of the thread, but it does not explain what the thread is used for~

NioEndpoint.startInternal()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Click to jump to this class, we can see that it has been implementedRunnableinterface, then we directly check hisrun()method to see its operating logic.

Poller.run()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

We can know from the comments that this thread is mainly used to poll the connected socket, check whether an event is triggered, and hand over the associated socket to the corresponding processor when the event occurs. In the source code we can seekeyCountVariables record the number of pending requests and provide them for subsequent judgments.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

keep going down throughkeyCountDetermine whether there is a request that needs to be processed, and if necessary, passselector.selectedKeys()get what needs to be processedchannelCollection, for loop processing. existwhileIn the loop we see that all ready channels call theprocessKey(sk, socketWrapper)method to process.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Click to jump to this method, where you can see that heskMake a read and write judgment. Since it is a request, it must be a read operation. Let’s take a look at the related methods first.

NioEndpoint.processKey()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

After entering, we can see that it first tries to obtain a processing thread in the cache pool. When there is no thread in the cache pool, it creates a new thread, and uses it directly if there is one.

AbstractEndpoint.processSocket()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Since it is a thread, then we only care about the core method of the thread. clickSocketProcessorBaseJump to viewrun()method.

SocketProcessorBase.run()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

existdoRun()Mark a breakpoint, click Next, and jump toNioEndpoint.doRun()method.PollerThe thread is handed over to the thread here for processing, in which the currentsocket, for further processing.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Once inside the method, we can see that it first calls thewrapperMake a judgment, take it out if it is not emptysocket, and then try theconnectionsto obtain the correspondingprocessor, if it cannot be obtained, try to obtain the connection that has been processed but has not been destroyedprocessorTo get it, create it if you can’t get it. This avoids frequent object creation and destruction.

AbstractProtocol.process()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

getprocessorAfter that, callprocessmethod to parse the message.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

After entering this method, we can see that there is a pair ofsocketEventTo judge the state, our current request is mainly to read the state, put a breakpoint here, and jump to this method to have a look.

AbstractProcessorLight.process()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Here we can see that we have enteredhttp11In the class, the message is parsed in this class, and the nativerequestandresponseobject. hereresponseBecause we haven’t reached the step of returning, we just make a preliminary parameter setting. to be passed in laterAdapterProceed to the next step.

Http11Processor.service()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

here for nativerequestandresponseconvert to getHttpServletRequestandHttpServletResponse. Then find the one that can handle the current request based on the request informationhostcontextwrapper

CoyoteAdapter.service()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

In this method you can see that it will passgetMapper()method to match the one that can handle the current requesthost,context,wrapper. Some friends here may wonder why it is frommapperto match? I leave this question to you to explore, and I will answer it for you in the next chapter.

CoyoteAdapter.postParseRequest()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

In the previous method, byconnectorObtainserviceand then get the correspondingmapper, but did not see themapperObject construction, where did the object come from?

Mapper.map()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

I don’t know if you still remember that in the second article, inStandardServicein classinitInternal()andstartInternal()method hasmapperListenerMethod initialization and startup.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

In this method find the correspondinghost, context, wrapper

Mapper.internalMap()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

back toCoyoteAdapter.postParseRequest(),passEvalusteWe can see the correspondinghost, context, wrapperand instance mappings are found.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

The next thing to do is to make a level-by-level call according to the link component until the final extractionservletimplement.

CoyoteAdapter.service()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

get firsthost, after passinghostContinue to call the next level component

StandardEngineValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

AbstractAccessLogValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

ErrorReportValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

get it herecontext,continueinvoke()

StandardHostValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

AuthenticatorBase.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

StandardContextValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

gotwrapperAfter that, continue to execute downwards, fromwrapperobtained in the containerservletobject.

StandardWrapperValve.invoke()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Next, put the obtainedservletAdd it to the filter chain (there may be other processing, which is not directly processed here), and it will be processed after calling the filter chain below.

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

ApplicationFilterChain.doFilter()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

Finally found a specific example, it is not easy! ! !

ApplicationFilterChain.internalDoFilter()

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

3. Summary

Tomcat Source Code Learning Part 4 - Servlet Request Analysis

I have collected manycomputer e-books, if you need it, please mention it yourself~