tomcat entry to mastery

Keywords: Java Tomcat

1, Tomcat Foundation

1.1.Tomcat Foundation

Tomcat It's essentially a Servle(Color is) Container, therefore Catalina(Katarina) is Tomcat Core of , Other modules are for Catalina(Katarina) Provide support. such as :  adopt Coyote (k The module provides link communication, Jasper(Jasper) Module provision JSP Engine, Naming provide JNDI Services, Juli Provide log service.
1). Software architecture
1. C/S:  client/Server side ‐‐‐‐‐‐‐‐‐‐‐‐> QQ , 360 ....
2. B/S:  browser/Server side ‐‐‐‐‐‐‐‐‐‐‐‐> JD.COM, Netease , TaoBao , Intelligence Podcast
Official website
2). Resource classification
1. Static resources: After all users access, the results are the same, which is called static resources. Static capital
The source can be parsed directly by the browser.
* For example: html,css,JavaScript,jpg
2. dynamic resource: After each user accesses the same resource, the results may be different , It is called dynamic capital
Source. After dynamic resources are accessed, they need to be converted into static resources first, and then returned to the browser for parsing through the browser.
* For example: servlet/jsp,php,asp....
3). Three elements of network communication
1. IP: Electronic equipment(computer)Unique identification in the network.
2. Port: the unique identification of the application in the computer. 0~65536
3. Transmission protocol: Specifies the rules for data transmission
1. Base agreement:
1. tcp : Security protocol, three handshakes. The speed is a little slow
2. udp: Unsafe protocol. speed

Why is there a TCP/IP protocol?

All over the world, various computers run different operating systems to serve everyone,
The methods used by these computers to express the same information are very different.
It's like God in the Bible disrupted the accents of people everywhere and made them unable to cooperate.
Computer users realize that computers are only individual operations and will not play a great role.
Only by combining them can the computer reach its maximum potential. So people
Trying to connect the computer with wires.

But simply connecting together is not enough. It's like two people with different languages meet each other,
Completely unable to exchange information. So they need to define something in common to communicate,
TCP/IP That's why I was born. TCP/IP It is not a protocol, but a general term of a protocol family.
It includes IP agreement, IMCP agreement, TCP agreement,
And what we are more familiar with http,ftp,pop3 Agreement, etc.
With these, the computer can communicate freely with other computer terminals as if it had learned a foreign language.

TCP/IP protocol layering TCP/IP protocol family is packaged layer by layer from top to bottom.

application layer:
Provide users with a set of common applications, such as e-mail, file transfer access, remote login, etc. Remote login TELNET use TELNET The protocol provides an interface registered on other hosts in the network. TELNET The session provides a character based virtual terminal. File transfer access FTP use FTP Protocol to provide file copy function between machines in the network.

Transport layer:
Provides communication between applications. Its functions include: first, formatting information flow; 2, Provide reliable transmission. In order to realize the latter, the transport layer protocol stipulates that the receiver must send back an acknowledgement and must resend if the packet is lost.

network layer :
Responsible for communication between adjacent computers. Its functions include three aspects.
1, Process the packet sending request from the transport layer, and load the packet after receiving the request IP Datagram, fill the header, select the path to the sink, and then send the datagram to the appropriate network interface.

2, Process the input datagram: first check its legitimacy, and then perform pathfinding--If the datagram has reached the sink, remove the header and give the rest to the appropriate transmission protocol; If the datagram has not yet reached the sink, forward the datagram.

3, Deal with routing, flow control, congestion and other problems.

Network interface layer:
This is TCP/IP The lowest layer of software, responsible for receiving IP The datagram is sent through the network, or the physical frame is received from the network and extracted IP Datagram, give it to IP Layer.

IP Is connectionless
IP Used for communication between computers.

IP Is a connectionless communication protocol. It does not occupy the communication line between two computers that are communicating. So, IP This reduces the demand for network lines. Each line can meet the communication needs between many different computers at the same time.

adopt IP,Messages (or other data) are divided into small independent packets and transmitted between computers through the Internet.

IP Responsible for routing each packet to its destination.

IP address
Each computer must have one IP Address to connect to the Internet.

each IP A package must have an address before it can be sent to another computer.

Each node on the network must have an independent Internet Address (also known as IP Address). Now, commonly used IP The address is a 32 bit That's what we often say IPv4 Standard, this is 32 bit The numbers are divided into four groups, the common The style of the. IPv4 On the standard, addresses are divided into five categories, which we often use B Class address. Please refer to other documents for specific classification. It should be noted that IP The address is the network number+Combination of host numbers, which is very important.

CP/IP use 32 A bit to address. A computer byte is 8 Bit. therefore TCP/IP Used 4 Bytes.
A computer byte can contain 256 Different values:
00000000,00000001,00000010,00000011,00000100,00000101,00000110,00000111,00001000 ....... until 11111111.
Now, you know why TCP/IP The address is between 0 reach 255 Between 4 A number.
TCP Use fixed connections
TCP Used for communication between applications.

When the application wants to pass TCP When communicating with another application, it sends a communication request. The request must be sent to an exact address. After the two sides "shake hands", TCP A full duplex will be established between the two applications (full-duplex) Communication.

This full duplex communication will occupy the communication line between two computers until it is closed by one or both sides.

UDP and TCP Very similar, but simpler, and less reliable TCP.

IP Router
Be a IP A packet is sent from a computer and it arrives at a IP Router.

IP The router is responsible for routing the packet to its destination, directly or through other routers.

In the same communication, the path of one packet may be different from that of other packets. The router is responsible for addressing correctly according to traffic, errors in the network or other parameters.

domain name
12 Arabic numerals are hard to remember. It's easier to use a name.

be used for TCP/IP The name of the address is called the domain name. Is a domain name.

When you type an image   Such a domain name, the domain name will be a   DNS   The program is translated into numbers.

In the world, a large number of DNS The server is connected to the Internet. DNS The server is responsible for translating the domain name into TCP/IP At the same time, they are responsible for updating each other's systems with the new domain name information.

When a new domain name together with its TCP/IP After the address is registered together, all over the world DNS The server updates this information.

TCP/IP signify TCP and IP Work together.

TCP Responsible for communication between application software (such as your browser) and network software.

IP Responsible for communication between computers.

TCP Be responsible for dividing and loading data IP Packages, and then reassemble them when they arrive.

IP Responsible for sending the package to the recipient.

TCP message format

16 Bit source port number: the 16 bit source port contains the port for initializing communication. Source port and source IP The address is used to identify the return address of the message.

16 Bit destination port number: the 16 bit destination port domain defines the destination of the transmission. This port indicates the application program address interface on the message receiving computer.

32 Bit serial number: the 32-bit serial number is used by the receiving computer, and the re segmented message is in the original form. When SYN It appears that the sequence code is actually the initial sequence code( Initial Sequence Number,ISN),And the first data byte is ISN+1. This sequence number (sequence code) can be used to compensate for inconsistencies in transmission.

32 Bit confirmation serial number: the 32-bit serial number is used by the receiving computer to reorganize the segmented message into the original form. If set ACK Control bit, which represents the sequence code of a packet to be received.

4 Header length: 4 bits TCP Header size, indicating where data starts.

Reserved (6 bits): 6-bit value field. These bits must be 0. Reserved for future use.

Flag: 6-bit flag field. It is expressed as: emergency flag, meaningful response flag, push, reset connection flag, synchronization serial number flag and completion of data transmission. The sequence is as follows: URG,ACK,PSH,RST,SYN,FIN.

16 Bit window size: used to represent each bit you want to receive TCP The size of the data segment. TCP The flow control of is provided by each end of the connection through the declared window size. The window size is the number of bytes, starting from the value indicated in the confirmation sequence number field, which is the byte expected to be received by the receiving end. The window size is a 16 byte field, so the maximum window size is 65535 bytes.

16 Bit checksum: 16 bits TCP Header. The source machine calculates a value based on the data content, and the receiver should match the value of the source machine The results are exactly the same, which proves the validity of the data. The test and cover the whole TCP Message segment: This is a mandatory field, which must be calculated and stored by the sender and verified by the receiver.

16 Bit emergency pointer: refers to the byte followed by priority data, in URG Only valid when the flag is set URG The flag is not set and the emergency field is filled. Speed up the processing of data segments marked as emergency.

Option: variable length, but the length must be 1 byte. If there is no option, it means that the 1-byte field is equal to 0.

Data: this TCP Data of protocol package load.
In the above fields, the functions of each option in the 6-bit flag field are as follows.

URG: Emergency sign. The emergency sign is"1"Indicates that this bit is valid.
ACK: Confirmation flag. Indicates that the confirmation number column is valid. In most cases, this flag bit is set. TCP The confirmation number contained in the confirmation number column in the header( w+1)It is the next expected sequence number and indicates that the remote system has successfully received all data.
PSH: Push flag. When this flag is set, the receiving end will not queue the data, but transfer the data to the application for processing as soon as possible Telnet or rlogin This flag is always set when connecting in interactive mode.
RST: Reset flag. Used to reset the corresponding TCP connect.
SYN: Synchronization flag. Indicates that the synchronization sequence number column is valid. This flag is established only after three handshakes TCP Valid when connecting. It prompts TCP The connected server checks the serial number, which is TCP The initial sequence number of the initial connection end (usually the client). Here, you can TCP The sequence number is regarded as a 32-bit counter ranging from 0 to 4294967295 TCP Each byte in the data exchanged by the connection is serially numbered TCP The serial number column in the header includes TCP The sequence number of the first byte in the segment.
FIN: End flag.

TCP triple handshake

(1)First handshake: Client((soon) put the flag in position SYN Set to 1 to randomly generate a value seq=J,And send the packet to Server,Client get into SYN_SENT Status, waiting Server Confirm.

(2)Second handshake: Server(Color me)Flag bit after receiving data packet SYN=1 know Client Request to establish a connection, Server Flag bit SYN and ACK All set to 1, ack=J+1,Randomly generate a value seq=K,And send the packet to Client To confirm the connection request, Server get into SYN_RCVD Status.

(3)Third Handshake: Client((almost) check after receiving the confirmation ack Is it J+1,ACK Whether it is 1. If it is correct, the flag bit will be ACK Set to 1, ack=K+1,And send the packet to Server(Color me),Server(Color me)inspect ack Is it K+1,ACK Whether it is 1. If it is correct, the connection is established successfully, Client and Server get into ESTABLISHED Status, complete three handshakes, and then Client((almost) and Server(Color me)Data transmission can begin between.

Simply put, it's

1,When a connection is established, the client sends SYN Package( SYN=i)To the server and into SYN-SEND Status, waiting for server confirmation

2,Server received SYN Package, the customer must be confirmed SYN(ack=i+1),Also send one yourself SYN Package( SYN=k),Namely SYN+ACK Package, and the server enters SYN-RECV state

3,Client received from server SYN+ACK Package and send a confirmation message to the server ACK(ack=k+1),After the package is sent, the client and server enter ESTABLISHED State, complete three handshakes, and the client and server start transmitting data.

TCP waved four times

because TCP The connection is full duplex. Therefore, each direction must be closed separately. This principle is that when one party completes the data transmission task, it sends one FIN To terminate the connection in this direction and receive a FIN It just means that there is no data flow in this direction, that is, no more data will be received, but in this direction TCP Data can still be sent on the connection until it is also sent in this direction FIN. The party that first performs the shutdown will perform the active shutdown, while the other party will perform the passive shutdown, as described in the above figure.

(1)First wave: Client Send a FIN,Used to close Client((almost) here Server(Color me)Data transmission, Client((almost) enter FIN_WAIT_1 Status.

(2)Second wave: Server(Color me)received FIN After, send a ACK to Client(Soon), confirm that the serial number is the received serial number+1(And SYN Same, one FIN Occupy a serial number), Server(Color me)get into CLOSE_WAIT Status.

(3)Third wave: Server Send a FIN,Used to close Server(Color me)reach Client(Fast data transmission, Server(Color me)get into LAST_ACK Status.

(4)Fourth wave: Client((almost) got it FIN After, Client get into TIME_WAIT Status, and then send a ACK to Server(Color me),Confirm that the serial number is the received serial number+1,Server(Color me)(Color me)get into CLOSED Status, complete four waves.

Why is establishing a connection three handshakes and closing a connection four waves?

This is because the server is LISTEN In status, the request to establish a connection is received SYN After the message, put ACK and SYN Send it to the client in a message. When closing the connection, when receiving the other party's FIN When sending a message, it only means that the other party no longer sends data, but can still receive data, and your party may not send all data to the other party, so you can send it immediately close(You can also send some data to the other party before sending it FIN Send a message to the other party to agree to close the connection now. Therefore, your own party ACK and FIN Usually sent separately.

1.2 Tomcat directory structure the main directory files of Tomcat are as follows:

bin / deposit Tomcat Batch script files such as start and stop of
startup.bat ,
Used in windows and linux Startup script under
shutdown.bat ,
Used in windows and linux Stop script under
conf / For storage Tomcat Related configuration files for
Catalina Used to store data for each virtual machine Context to configure
Used to define all web All applications need to be loaded Context match
Set, if web The app specified its own context.xml
,The file will be overwritten Tomcat Environment variable configuration for
catalina.policy Tomcat Running security policy configuration
Tomcat Log profile, This file can be used for revision
change Tomcat Log level and log path, etc
server.xml Tomcat Core profile of the server
tomcat-users.xml definition Tomcat Default user and role mapping information configuration
Tomcat The default deployment description file for all applications in the, main
To define the basis Servlet and MIME Mapping.
lib / Tomcat Server dependent packages
logs / Tomcat Default log storage directory
webapps / Tomcat default Web Application deployment directory
work / Web application JSP Temporary directory for code generation and compilation

2, Tomcat architecture 2.1 working principle of HTTP

HTTP Protocol is the data transfer protocol between browser and server. As an application layer protocol, HTTP Is based on TCP/IP
Protocol to transfer data( HTML Files, pictures, query results, etc.), HTTP The protocol does not involve packets
(Packet)Transmission, which mainly specifies the communication format between the client and the server.

As you can see from the figure, the process is:

1) The user makes an operation through the browser, such as entering the website and entering, or clicking a link and browsing
The event was retrieved by the.
2) The browser sends a message to the server TCP Connection request.
3) The service program accepts the connection request from the browser and passes through TCP Three handshakes establish a connection.
4) The browser packages the request data into a HTTP Packet in protocol format.
5) The browser pushes the data packet into the network, and the data packet is transmitted through the network and finally reaches the end service program.
6) After the server program gets the packet, it also uses HTTP Unpack the protocol format to obtain the intention of the client.
7) After knowing the intention of the client, process it, such as providing static files or calling the server program to obtain dynamic results.
8) The server will respond to the result (possibly HTML Or pictures, etc.) according to HTTP Protocol format packaging.
9) The server pushes the response data packet into the network, and the data packet is transmitted through the network and finally reaches the browser.
10) After the browser gets the packet, click HTTP Unpack the protocol format, and then parse the data, assuming that the data here is
11) Browser will HTML The file is displayed on the page.
That's what we want to explore Tomcat As a HTTP Server, what have you done in this process? main
If you accept the connection, parse the request data, process the request and send the response.

2.2 Http server request processing

The browser sends a request in HTTP format to the server. After receiving this request, the HTTP server needs to call the server program to process it. The so-called server program is the Java class you write. Generally speaking, different requests need to be processed by different Java classes.

1) Figure 1 , express HTTP The server directly calls specific business classes, which are tightly coupled.
2) Figure 2, HTTP Instead of calling the business class directly, the server gives the request to the container for processing
Servlet(The interface with color () calls the business class. therefore Servlet((color) interface and Servlet(The appearance of the container (with color) has reached HTTP Server and
The purpose of business class decoupling. and Servlet((color) interface and Servlet(The whole set of specifications for (color) containers is called Servlet(Color specification.
Tomcat according to Servlet(The requirements of the color specification are realized Servlet((color) containers, and they also have HTTP Server function
Yes. As Java Programmers, if we want to implement new business functions, we only need to implement one Servlet(Color) and put it
Register to Tomcat(Servlet In the container, the rest is left to Tomcat Took care of it for us.

3, Servlet container workflow

To decouple, HTTP The server does not call directly Servlet(Color), but give the request to Servlet((color) container to deal with, that
Servlet(How does the container work?
When a customer requests a resource, HTTP The server will use a ServletRequest(Colored Seal the customer's request information for the fast object
Put it up and call it. Servlet(Color of container service((color) method, Servlet((color) after the container receives the request, according to the requested URL
and Servlet(The mapping relationship of (with color) and find the corresponding Servlet(Color), if Servlet(Before it is loaded, it is created by reflection mechanism
Build this Servlet(Color), and call Servlet(Colored) init(in Method to complete initialization, and then call Servlet(Colored) service(Color method
To handle the request ServletResponse(Colored Object of Ruibang returned to HTTP The server, HTTP The server sends the response to

IV. overall architecture of Tomcat

We know that if we want to design a system, we first need to understand the requirements. We have learned that Tomcat needs to realize two core functions: 1) handle Socket connections and be responsible for the conversion of network byte streams to Request and Response objects. 2) Load and manage servlets (colored) and specifically handle Request (Rui dying) requests. Therefore, Tomcat has designed two core components: Connector (durable) and Container (heat lifting) to do these two things respectively. The Connector is responsible for external communication, and the Container is responsible for internal treatment. Five connectors - Coyote (k with you)

Coyote(k (with you) yes Tomcat Name of the connector frame , yes Tomcat An external connection provided by the server for client access
Mouth. Client pass Coyote(k You can connect to the server, send requests, and receive responses .
Coyote Encapsulates the underlying network communication( Socket(Less change) Request and response processing) Catalina(card Pagoda 
Lina) container provides a unified interface to make Catalina(Catalina) container and specific request agreement and IO The operation mode is completely decoupled. Coyote(k (with you) take Socket(Less change) transport
The input conversion package is Request (Rui's dying) object, leave it to Catalina(card Pagoda (Lina) The container processes the request. After the processing request is completed, Catalina(Katarina) through
too Coyote(k (with you) Provided Response(Rui die (bang die) Object writes the result to the output stream .
Coyote (k As an independent module, you are only responsible for specific protocols and IO Operations related to, And Servlet(Color) Specification implementation has no direct
Connection, so even Request(Rui (dying) and Response(Rui die (bang die) Object is not implemented Servlet(The interface corresponding to the (color) specification, and
Yes Catalina Further encapsulate them as ServletRequest(Colored (faster) and ServletResponse(Colored Ruibang's) .

6, IO model and protocol

stay Coyote(k Yes, you are , Tomcat Multiple supported I/O What are the model and application layer protocols IO Model and application layer
Please refer to the following table for the agreement:
Tomcat Supportive IO Model (from 8.5/9.0 From version, Tomcat Removed yes BIO Supported by:
1st floor, jinyanlong office building, Jiancai Chengxi Road, Changping District, Beijing Tel: 400-618-9090
IO Model
NIO Non blocking I/O,use Java NIO Class library implementation.
NIO2 asynchronous I/O,use JDK 7 abreast of the times NIO2 Class library implementation.
use Apache Portable runtime implementation, yes C/C++Write a local library. If this option is selected, it needs to be installed separately APR Library.
Application layer collaboration
HTTP/1.1 This is most Web The access protocol adopted by the application.
For and Web Server Integration (e.g Apache),In order to optimize static resources and cluster deployment, it is currently supported AJP/1.3.
HTTP 2.0 Greatly improved Web Performance. Next generation HTTP agreement , Since 8.5 And 9.0 Supported after version.
Tomcat Supported application layer protocols :
Protocol layering :
stay 8.0 before , Tomcat Default I/O The method is BIO , Later read NIO.  whether NIO,NIO2 still APR, The performance is better than the previous ones BIO.  If used APR, Can even reach Apache HTTP
Server(Color) Affect performance.
Tomcat In order to support multiple I/O For model and application layer protocols, a container may dock multiple connectors, just like
A room has multiple doors. However, no single connector or container can provide external services. They need to be assembled
It can only work when it is assembled. This whole is called Service Components. Please note here, Service I didn't do anything myself
What's important is to wrap an extra layer outside the connector and container and assemble them together. Tomcat Neike
Can there be more than one Service(This design is also for flexibility. Through in Tomcat Configure multiple in
Service(Color), you can access different applications deployed on the same machine through different port numbers.

Connector assembly The functions of each component in the connector are as follows:

EndPoint(an (guaranteed)
1) EndPoint(an (guaranteed) :  Coyote(k (with you) The communication endpoint, that is, the interface for communication monitoring, is specific Socket(Less modification) reception and transmission processing
Is an abstraction of the transport layer, so EndPoint(Abstract)Used to implement TCP/IP Agreed.
2) Tomcat did not EndPoint(an (guaranteed) Interface, but provides an abstract class AbstractEndpoint (Ah's dead catch an (guaranteed)
Two inner classes are defined: Acceptor and SocketProcessor. Acceptor For listening Socket Connection request.
SocketProcessor Used to process received Socket Request, it implements Runnable Interface, in Run Method inside
Call protocol processing component Processor Process. In order to improve processing capacity, SocketProcessor Submitted to
Thread pool to execute. This thread pool is called an executor( Executor),I'll cover it in detail in a later column
Tomcat How to extend native Java Thread pool.
Processor :  Coyote Protocol processing interface ,if EndPoint Is used to implement TCP/IP Agreement, then
Processor Used to implement HTTP agreement, Processor Receive from EndPoint of Socket,Read byte stream solution
Decompose into Tomcat Request and Response Object, and through Adapter Submit it to the container for disposal,
Processor It is an abstraction of the application layer protocol.
ProtocolHandler(Running test Cold heat)

ProtocolHandler:  Coyote Protocol interface, adopt Endpoint and Processor , Implement specific collaboration
The processing capacity of the system. Tomcat In accordance with the agreement and I/O Six implementation classes are provided :  AjpNioProtocol ,
AjpAprProtocol, AjpNio2Protocol , Http11NioProtocol ,Http11Nio2Protocol ,
Http11AprProtocol. We're configuring tomcat/conf/server.xml Time , At least specify a specific
ProtocolHandler , Of course, you can also specify a protocol name , as :  HTTP/1.1 ,If installed APR,that
Will use Http11AprProtocol , Otherwise use Http11NioProtocol .
Adapter(Po's hot)
Due to different protocols, the request information sent by the client is also different, Tomcat Defined their own Request class
To "store" these request information. ProtocolHandler The interface is responsible for parsing the request and generating Tomcat Request Class.
But this Request Object is not standard ServletRequest,Which means you can't use it Tomcat
Request Call the container as a parameter. Tomcat The designer's solution is to introduce CoyoteAdapter,This is
Classic application of adapter mode, connector call CoyoteAdapter of Sevice Method, passed in is Tomcat
Request Object, CoyoteAdapter Be responsible for Tomcat Request Turn into ServletRequest,Re call volume
Instrumental Service method.

7, Catalina structure

 Catalina(Catalina) The main components of the are as follows:

Responsible for analysis Tomcat Configuration file for , To create a server Server(Component in color, and according to
Command to manage it
The server represents the entire Catalina Servlet((color) container and other components, responsible for assembly and start-up
Servlet(Color engine,Tomcat Connector. Server Through implementation Lifecycle(Hungry color button
Interface, providing
An elegant way to start and shut down the entire system
Service is Server(Color) internal components, one Server(Color) contains multiple Service. It will be several
Component is bound to a Container((liftable)
The connector handles the communication with the client. It is responsible for receiving the client's request and then forwarding it to the relevant server
And finally return the response result to the customer
Container((available) Container, responsible for handling user's servlet Request and return the object to web User's module
Container((available) structure
Tomcat Four kinds of containers are designed Engine,Host,Context and Wrapper. These four containers are not flat
Line relationship, but parent-child relationship., Tomcat Through a layered architecture, the Servlet The container has good flexibility
Meaning of each component :
Engine(EN Jing)
Represents the whole Catalina of Servlet Engine, used to manage multiple virtual sites, one Service
There can only be one at most Engine,However, an engine can contain more than one Host
Host(Thick dead)
Represents a virtual host, or a site, that can give Tomcat Configure multiple virtual hosts
Machine address, and a virtual host can contain multiple addresses Context
Context(Kang text)
Represents a Web Applications, One Web The application can contain multiple applications Wrapper
Wrapper (Oh, newspaper
Represents a Servlet,Wrapper As the lowest level in a container, it cannot contain child containers
We can also pass again Tomcat of server.xml Profile to deepen the Tomcat Understanding of containers. Tomcat
The component design is adopted, and its constituent components are configurable, of which the outermost layer is Server,Other components
It is configured in this top-level container according to certain format requirements.
So, Tomcat How do you manage these containers? You will find that these containers have a parent-child relationship to form a tree
Shape structure, you may immediately think of the combination pattern in the design pattern. you 're right, Tomcat Is to use the combination mode
Manage the of these containers. The specific implementation method is that all container components are implemented Container Interface, so combined mode
The formula can make users use single container objects and composite container objects consistently. Here, a single container object refers to
It's the bottom Wrapper,The composite container object refers to the above Context,Host perhaps Engine.

VIII. Tomcat startup process

 step :
1) start-up tomcat , Need to call bin/startup.bat (stay linux Directory , Need to call bin/
, stay startup.bat In script, Called catalina.bat.
2) stay catalina.bat In the script file, it is called. BootStrap Medium main method.
3)stay BootStrap of main Method is called init method , To create Catalina and Initialize the class loader.
4)stay BootStrap of main Method is called load method , Called again in it Catalina of load square
5)stay Catalina of load Method , Some initialization is required, And need to construct Digester object, use
Yu analysis XML.
6) Then, the initialization operation of subsequent components is called . . .
load Tomcat To initialize the container component ,Listen for the corresponding port number, Ready to accept client requests
Because all components have life cycle methods such as initialization, start and stop, they have the characteristics of life cycle management
Sex, therefore Tomcat When designing, Based on life cycle management, it is abstracted into an interface Lifecycle ,And group
piece Server,Service,Container,Executor,Connector assembly , All achieve a life cycle
Interface, thus having the following core methods in the life cycle:

1) init(): Initialize component  in Resistant
2) start(): Start component   Dead lead
3) stop(): Stop component    Dead Guide
4) destroy(): Destroy components  Drip dead Guide

Default implementation of each component

We mentioned above Server,Service,Engine,Host,Context All interfaces, This is listed in the figure below
Default implementation classes for these interfaces. Current for Endpoint For components, in Tomcat There is no corresponding in Endpoint
Interface, But there is an abstract class AbstractEndpoint ,There are three implementation classes: NioEndpoint,
Nio2Endpoint,AprEndpoint , These three implementation classes correspond to the linker explained earlier Coyote
When, The linker mentioned supports three IO Model: NIO,NIO2,APR , Tomcat8.5 In version, the default is
With NioEndpoint(Cow press run in of
We mentioned above Server,Service,Engine,Host,Context All interfaces, This is listed in the figure below
Default implementation classes for these interfaces. Current for Endpoint For components, in Tomcat There is no corresponding in Endpoint
Interface, But there is an abstract class AbstractEndpoint ,There are three implementation classes: NioEndpoint,
Nio2Endpoint,AprEndpoint , These three implementation classes correspond to the linker explained earlier Coyote
When, The linker mentioned supports three IO Model: NIO,NIO2,APR , Tomcat8.5 In version, the default is
With NioEndpoint. Cow press run in of

IX. Tomcat request processing flow

Request process

With so many levels of containers designed, Tomcat How do you determine which request should be sent by Wrapper(WOW (POP)
In the container
Servlet To deal with? The answer is, Tomcat Yes Mapper(Maipu
Component to complete this task.
Mapper The function of the component is to transfer the information requested by the user URL Navigate to a Servlet,Its working principle is:
Mapper Saved in the component Web The application configuration information is actually the mapping relationship between the container component and the access path,
such as Host The domain name configured in the container Context In the container Web Application path, and Wrapper In the container
Servlet Mapping path, you can imagine that these configuration information is a multi-level Map.

When a request comes, Mapper The component parses the request URL The domain name and path in, and then to your own saved domain name
Map You can locate one if you look in it Servlet. Please note that there is a request URL Finally, only one will be located
Wrapper Container, that is, a Servlet.
In the diagram below , Just describe it When a user requests a link   of
after, How to find the final processing business logic servlet .
The picture above only describes the request URL How to find the to be executed Servlet , So let's
Let's analyze it again , from Tomcat Analysis at the design architecture level Tomcat Request processing.

The steps are as follows:
1) Connector(Tolerable)assembly Endpoint(and In the race Acceptor Listen for client socket connections and receive Socket(Less modified).
2) Hand over the connection to the thread pool Executor(in Heat of k Start the request response task.
3) Processor(The running card (dead) component reads the message, parses the request line, request body and request header, and encapsulates them into Request(Ray's dying) object.
4) Mapper(Maipu)Component based on request line URL Value and request header Host Which values match Host Containers Context(Kang text Capacity
Device Wrapper(I) container processing request.
5) CoyoteAdaptor(Can you press the (killed) component responsible for Connector(Tolerable)Components and Engine(Um, Jing)Associated with the container
Request(Rui (dying) object and response object Response(Rui die (bang die) passed to Engine(In the container, call Pipeline(It doesn't work.
6) Engine(Well, the treatment is started through the pipeline of the container, which contains several Valve,each Valve Responsible for partial processing logic
Edit. End of execution Valve The basic will be executed later Valve--StandardEngineValve,Responsible for calling Host Container
Pipeline(It doesn't work.
7) Host The pipeline of the container starts processing, and the process is similar. Finally, it is executed Context Container Pipeline(It doesn't work.
8) Context The pipeline of the container starts processing, and the process is similar. Finally, it is executed Wrapper Container Pipeline(It doesn't work.
9) Wrapper The pipeline of the container starts processing, and the process is similar. Finally, it is executed Wrapper Container corresponding Servlet object
of Treatment method.
stay Tomcat Defined in Pipeline (And Valve Two interfaces, Pipeline (It is used to build the responsibility chain, The latter represents responsibility
Each processor on any chain. Pipeline((not pressed) A basic is maintained in Valve,It is always in Pipeline End of
(Finally, it encapsulates the specific process of request processing and output response. Of course, we can also call
addValve()method, by Pipeline (Add other Valve, Added after Valve Located on the foundation Valve of
Before and in the order of addition. Pipiline(Get the first one by Valve To start the implementation of the integration chain .

10, Jasper

Jasper(Run after death
brief introduction

For based JSP of web For applications, we can directly JSP Write in page Java Code, add third-party
Tag library, and use EL expression. However, no matter what form of processing, the final output to the client is
Standard HTML Page (including js ,css...),Does not contain any java Related syntax. in other words, I
We can put jsp It is regarded as a script running on the server. So how does the server JSP Page conversion to
HTML What about the page?
Jasper Module is Tomcat of JSP Core engine, we know JSP Is essentially a Servlet. Tomcat use
Jasper yes JSP Parse the syntax and generate Servlet And generate Class Bytecode, user accessing jsp When, will
visit Servlet,Finally, the results of the access will be directly responded to on the browser side . In addition, when running, Jasper still
Can detect JSP Whether the file is modified. If modified, it will be recompiled JSP File.

JSP compilation mode

Tomcat Will not start Web Automatically compile when applying JSP Documents, But when the client first requests,
To compile the files that need to be accessed JSP File.
Create a web project, And write JSP code :
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF‐8" language="java" %>
<%@ taglib prefix="c" uri="" %>
DateFormat dateFormat = new SimpleDateFormat("yyyy‐MM‐dd
String format = dateFormat.format(new Date());
Hello , Java Server Page . . . .
<%= format %>

Compilation process

Tomcat configures an org.apache.jasper.servlet.JspServlet in the default web.xml to process all requests ending in. jsp or. jspx. The Servlet implementation is the entry for runtime compilation.

Tomcat In the default web.xml One is configured in org.apache.jasper.servlet.JspServlet,Used at
Take care of everything.jsp or .jspx At the end of the request, the Servlet The implementation is the entry to runtime compilation.

Posted by lc on Sun, 05 Dec 2021 11:23:07 -0800