Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Tomcat work and what is the process of processing requests

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the working principle of Tomcat and the relevant knowledge of what the request process is, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on the working principle of Tomcat and processing request flow. Let's take a look at it.

Functional component structure

Core principles of Tomcat Connector

Tomcat Connector Framework-- Coyote

Connector core function

First, monitor the network port, receive and respond to network requests.

Second, network byte stream processing. Convert the received network byte stream to Tomcat Request and then to the standard ServletRequest to the container, and at the same time convert the ServletResponse sent from the container to Tomcat Response and then to the network byte stream.

Connector module design

To meet the two core functions of the connector, we need a communication endpoint to listen on the port; a processor to handle the network byte stream; and finally, an adapter to convert the processed result to the structure required by the container.

The corresponding source package path org.apache.coyote. The corresponding structure diagram is as follows

Core principle of Tomcat container

Tomcat Container Framework-- Catalina

Container structure analysis

Each Service contains a container. The container can manage multiple virtual hosts by one engine. Each virtual host can manage multiple Web applications. Each Web application will have multiple Servlet wrappers. Engine, Host, Context and Wrapper, the four containers belong to the parent-child relationship.

The corresponding source package path org.apache.coyote. The corresponding structure diagram is as follows

Container request processing

The request processing of the container is called layer by layer between the four containers: Engine, Host, Context and Wrapper, and finally the corresponding business logic is executed in Servlet. Each container will have a channel Pipeline, and each channel will have a Basic Valve (such as StandardEngineValve), similar to a gate for handling Request and Response. The flow chart is as follows.

Tomcat request processing flow

The above knowledge points have been introduced in bits and pieces of how an Tomcat handles a request. Simple understanding is the connector processing flow + container processing flow = Tomcat processing flow. Ha! So the question is, how does Tomcat find the corresponding virtual site through the request path? How to find the corresponding Servlet?

Introduction to the function of mapper

Here you need to introduce a component Mapper that is not described above. As the name implies, its purpose is to provide a route map for the request path. Which container is used to match the request URL address. Each of these containers has its own corresponding Mapper, such as MappedHost. I don't know if you recall the fear of being dominated by Mapper class not found. In the past, every time you write a complete function, you need to configure mapping rules in web.xml. When the file becomes larger and larger, various problems will arise.

HTTP request process

Open the server.xml file in the tomcat/conf directory to parse an http://localhost:8080/docs/api request.

Step 1: the port on which the connector listens is 8080. Because the requested port is the same as the listening port, the connector accepts the request.

Step 2: because the default virtual host for the engine is localhost, and the directory of the virtual host is webapps. So the request found the tomcat/webapps directory.

Step 3: the parsed docs is the application name of the web program, which is context. At this point, the request continues to find the docs directory from the webapps directory. Sometimes we also omit the application name.

Step 4: the parsed api is the specific business logic address. At this point, you need to find the mapping relationship from docs/WEB-INF/web.xml, and finally call the specific function.

How SpringBoot starts the embedded TomcatSpringBoot button to start the service, so that many people who have just entered the society forget what Tomcat is. With the increasing performance of hardware, ordinary small and medium-sized projects can be started directly with built-in Tomcat. But some larger projects may use Tomcat clustering and tuning, and the built-in Tomcat may not be able to meet the requirements. Let's first analyze how SpringBoot starts Tomcat from the source code. Here is the code for SpringBoot 2.x. The code starts with the main method and executes the run method to start the project. SpringApplication.run clicks in from the run method to find a way to refresh the application context. This.prepareContext (context, environment, listeners, applicationArguments, printedBanner); this.refreshContext (context); this.afterRefresh (context, applicationArguments); click in from the refreshContext method and find the refresh method. And find the method of its parent class layer by layer. This.refresh (context); in the refresh method of the AbstractApplicationContext class, there is a line of logic that invokes the child container refresh. This.postProcessBeanFactory (beanFactory); this.invokeBeanFactoryPostProcessors (beanFactory); this.registerBeanPostProcessors (beanFactory); this.initMessageSource (); this.initApplicationEventMulticaster (); this.onRefresh (); this.registerListeners (); this.finishBeanFactoryInitialization (beanFactory); this.finishRefresh (); enter the onRefresh method to find the implementation of ServletWebServerApplicationContext. I finally see hope here. Protected void onRefresh () {super.onRefresh (); try {this.createWebServer ();} catch (Throwable var2) {throw new ApplicationContextException ("Unable to start web server", var2);}} click in from the createWebServer method to find the code to get the WebServer from the factory class. If (webServer = = null & & servletContext = = null) {ServletWebServerFactory factory = this.getWebServerFactory (); / / get web server this.webServer = factory.getWebServer (new ServletContextInitializer [] {this.getSelfInitializer ()});} else if (servletContext! = null) {try {/ / launch web server this.getSelfInitializer (). OnStartup (servletContext);} catch (ServletException var4) {throw new ApplicationContextException ("Cannot initialize servlet context", var4) }} click on the getWebServer method to find the implementation of TomcatServletWebServerFactory, along with Jetty and Undertow. Basic connectors, engines, virtual sites, and so on are configured here. Public WebServer getWebServer (ServletContextInitializer... Initializers) {Tomcat tomcat = new Tomcat (); File baseDir = this.baseDirectory! = null? This.baseDirectory: this.createTempDir ("tomcat"); tomcat.setBaseDir (baseDir.getAbsolutePath ()); Connector connector = new Connector (this.protocol); tomcat.getService (). AddConnector (connector); this.customizeConnector (connector); tomcat.setConnector (connector); tomcat.getHost (). SetAutoDeploy (false); this.configureEngine (tomcat.getEngine ()); Iterator var5 = this.additionalTomcatConnectors.iterator () While (var5.hasNext ()) {Connector additionalConnector = (Connector) var5.next (); tomcat.getService (). AddConnector (additionalConnector);} this.prepareContext (tomcat.getHost (), initializers); return this.getTomcatWebServer (tomcat) } after the service starts, the log o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat initialized with port (s): 8900 (http) o.apache.catalina.core.StandardService: Starting service [Tomcat] org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat/8.5.34o.a.catalina.core.AprLifecycleListener: The APR based Apache Tomcat Native library which allows optimal... o.a.c.c..Tomcat] .[ localhost]. [ /]: Initializing Spring embedded WebApplicationContexto.s.web.context.ContextLoader: Root WebApplicationContext: initialization completed in 16858 ms I feel like I find out why better companies ask about the underlying source code of the technology. Because in the process of looking at the source code is really interesting, and can find a lot of problems, and it is really a test of logical thinking and patience, I look at the tomcat source code, the day has passed, not finished, this is still under the premise that I am already very familiar with tomcat, ha, follow me, and then slowly update it later and finally introduce a document to you. This is also the book I refer to most in the process of parsing tomcat. The internal knowledge basically covers the relevant content of tomcat, from architecture design to configuration to clustering to performance optimization and expansion, etc., all-round analysis of tomcat, friends in need can follow + forward, private messages "source code" can view the access mode tomcat architecture tomcat configuration management tomcat security tomcat tuning tomcat additional features, only show this part If you need more Java-related learning documents, videos, follow me, you can get information about "how Tomcat works and what is the process of handling requests". Thank you for reading this article. I believe you all have a certain understanding of "how Tomcat works and what is the process of handling requests". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report