Understand the core knowledge points of Tomcat in one article

architecture

First, take a look at the entire architecture diagram. The most comprehensive Java interview site

Let me briefly explain it next.

Server : server. Tomcat is a Server server.

Service : There can be multiple services in the server, but only one service is included in the Tomcat of our commonly used Catalina container, and the connector and container are included in the service. A complete Service can complete the receiving and processing of requests.

Connectors : Coyote is a concrete implementation of connectors. Used to establish a connection with incoming requests and parse data. Because the IO models supported by Tomcat include NIO, NIO2, and APR, and the supported application layer protocols include HTTP1.1, HTTP2, and AJP. Therefore, for different IO models and application layer protocol requests, there can be multiple connectors in one Service to apply IO requests of different protocols.

EndPoint: Coyote communication endpoint, that is, the interface of communication monitoring, is the specific Socket receiving and sending processor, and is used to realize the TCP/IP transmission protocol.

Acceptor: The socket used to receive requests.

Executor: thread pool, after receiving the requested socket, one will be allocated from the thread pool to perform subsequent operations.

Processor: The Coyote protocol processing interface is used to implement the HTTP application layer protocol. It receives the Socket byte stream from the EndPoint and the container, and parses it into a request or response object.

ProtocolHandler: Coyote protocol interface, through EndPoint and Processor, realizes the processing capability for specific protocols.

Adapter: The container is only responsible for processing data. For data with different request protocols, the container will not be able to process it. Therefore, after the ProtocolHandler processes the generated request object, it needs to be converted into a ServletRequest object in a unified format defined by Tomcat. Adapter is used perform such an operation.

This article has been included in the Github warehouse, which includes computer foundation, Java foundation, multithreading, JVM, database, Redis, Spring, Mybatis, SpringMVC, SpringBoot, distributed, microservices, design patterns, architecture, school recruitment and social recruitment sharing, etc. Core knowledge points, welcome to star~

Github address

If you can't access Github, you can access the gitee address.

gitee address

Container : The core component of Tomcat, used to process requests and return data. Catalina is its concrete implementation.

Engine: It represents the Servlet engine of the entire Catalina, which is used to manage multiple virtual sites. A Service can only have one Engine at most. But an Engine can contain multiple Hosts.

Host: Indicates a host address, or a site, and multiple Contexts can be configured under a Host.

Context: Indicates a web application, a web application can contain multiple Wrappers

Wrapper: Represents a Servlet, which is the lowest component in the container.

The proportional relationship of each component

Implementation and execution of each component

Component implementation

Each component name mentioned above is an interface or abstract method, and its subclass or implementation class is executed when the request is actually processed.

Server, Service, Engine, Host, and Context are all interfaces, and the default implementation classes of these interfaces are listed in the figure below.

The implementation of Adapter is CoyoteAdapter

For the Endpoint component, there is no corresponding Endpoint interface in Tomcat, but there is an abstract class AbstractEndpoint, under which there are three implementation classes: NioEndpoint, Nio2Endpoint, AprEndpoint, these three implementation classes correspond to the previous explanation of the linker Coyote , The three IO models supported by the linker mentioned: NIO, NIO2, APR, in the tomcat8.5 version, NioEndpoint is used by default.

ProtocolHandler: Coyote protocol interface, by encapsulating Endpoint and Processor, it realizes the processing function for specific protocols. Tomcat provides 6 implementation classes according to the protocol and IO.

Let me share with you a Github warehouse, which contains more than 300 classic computer book PDFs compiled by Dabin, including C language, C++, Java, Python, front-end, database, operating system, computer network, data structure and algorithm, machine learning, Programming life , etc., you can star it, next time you look for a book directly search on it, the warehouse is continuously updated~

Github address

AJP agreement:

1) AjpNioProtocol: adopts the IO model of NIO.

2) AjpNio2Protocol: adopts the IO model of NIO2.

3) AjpAprProtocol: The IO model using APR needs to depend on the APR library.

HTTP protocol:

1) Http11NioProtocol : Adopt the IO model of NIO, the protocol used by default (if the server does not have APR installed).

2) Http11Nio2Protocol: adopts the IO model of NIO2.

3) Http11AprProtocol: The IO model using APR needs to depend on the APR library.

These components all have cycle methods such as initialization, start, and stop, so Tomcat designed a LifeCycle interface to define the common methods that need to be executed in the life cycle of these components. These component implementation classes all implement this interface.

start process

1) To start tomcat, you need to call bin/startup.bat (in the linux directory, you need to call bin/startup.sh), in

In the startup.bat script, catalina.bat is called.

2) In the catalina.bat script file, the main method in BootStrap is called.

3) The init method is called in the main method of BootStrap to create Catalina and initialize the class loader.

4) The load method is called in the main method of BootStrap, and the load method of Catalina is called in it.

5) In the load method of Catalina, some initialization work is required, and a Digester object needs to be constructed for parsing XML.

6) Then call the initialization operation of subsequent components. . .

Load the Tomcat configuration file, initialize the container component, listen to the corresponding port number, and prepare to accept client requests.

In short, each component executes the init() and start() methods step by step.

Implementation process

When a request enters Tomcat, the execution is as follows (because Tomcat has only one Service, so the Service and Engine are written in the same box below):

The positioning is mainly realized through the Mapper component, which is essentially a K and V key-value pair. When parsing, the request URL will be parsed first, and the Host part will be stored in the hosts attribute (MappedHost array in the Mapper class, saving all Host information), and then parse the Context part after finding it. In the MapperHost, there is also a contextList attribute (save all context information), and then look down, and finally get the corresponding Servlet and execute it.

In addition, in order to enhance the scalability between components, Tomcat defines two interfaces, Pipeline and Valve. Pipeline is used to build the chain of responsibility, which represents each processor on the chain of responsibility. A basic Valve is maintained in the Pipeline, which is always located at the end of the Pipeline (executed last), and encapsulates the process of specific request processing and output response. Of course, we can also call the addValve() method to add other Valves to the Pipeline, and the added Valve is located before the basic Valve and executed in the order of addition. Pipiline starts the execution of the integration chain by obtaining the first Valve.

So the final execution is as follows:

Proceed as follows:

1) The Acceptor in the Connector component Endpoint listens to the client socket connection and receives the Socket.

2) Hand over the connection to the thread pool Executor, and start executing the request response task.

3) The Processor component reads the message message, parses the request line, request body, and request header, and encapsulates it into a Request object.

4) The Mapper component matches which Host container, Context container, and Wrapper container process the request according to the URL value of the request line and the Host value of the request header.

5) The CoyoteAdaptor component is responsible for associating the Connector component with the Engine container, passing the generated Request object and response object Response to the Engine container, and calling the Pipeline.

6) The pipeline of the Engine container starts processing. The pipeline contains several Valves, and each Valve is responsible for part of the processing logic. After the Valve is executed, the basic Valve–StandardEngineValve will be executed, which is responsible for calling the Pipeline of the Host container.

7) The pipeline of the Host container starts to process, the process is similar, and finally the Pipeline of the Context container is executed.

8) The pipeline of the Context container starts to process, the process is similar, and finally the Pipeline of the Wrapper container is executed.

9) The pipeline of the Wrapper container starts to process, and the process is similar, and finally executes the processing method of the Servlet object corresponding to the Wrapper container.

configuration file

First look at the directory structure of tomcat

The core configuration file is in the conf directory

Server.xml (emphasis)

The most important of these is server.xml, which mainly configures all the configurations of the tomcat container. Let's take a look at the configurations.

Server

Is the root element of server.xml, used to create a Server instance, the default implementation is

<Server port="8005" shutdown="SHUTDOWN"> 
... 
</Server>

port: The port of the shutdown server that Tomcat listens to

shutdown: The command string to shut down the server.

The sub-elements embedded in Server are Listener, GlobalNamingResources, and Service.

The meaning of the five Listeners configured:

<!-- 用于以日志形式输出服务器 、操作系统、JVM的版本信息 --> 
<Listener className="org.apache.catalina.startup.VersionLoggerListener" /> 

<!-- 用于加载(服务器启动) 和 销毁 (服务器停止) APR。 如果找不到APR库, 则会输出日志, 并 不影响Tomcat启动 --> 
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> 

<!-- 用于避免JRE内存泄漏问题 -->
 <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

<!-- 用户加载(服务器启动) 和 销毁(服务器停止) 全局命名服务 --> 
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 

<!-- 用于在Context停止时重建Executor 池中的线程, 以避免ThreadLocal 相关的内存泄漏 -->
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

The global naming service is defined in GlobalNamingResources

Service

Used to create a Service instance, the embedded elements are: Listener, Executor, Connector, Engine , where: Listener is used to add a lifecycle listener to the Service, Executor is used to configure the shared thread pool of the Service, and Connector is used to configure the links contained in the Service Engine is used to configure the Servlet container engine corresponding to the linker in the Service. The default Service is called Catalina.

Executor

By default, Service does not configure a shared thread pool, and each connector uses its own thread pool (the default size is 10). If we want to add a thread pool, we can add the following configuration in the Service tag

<Executor name="tomcatThreadPool" 
    namePrefix="catalina-exec-" 
    maxThreads="200" 
    minSpareThreads="100" 
    maxIdleTime="60000" 
    maxQueueSize="Integer.MAX_VALUE"                 
   prestartminSpareThreads="false" threadPriority="5" 
  className="org.apache.catalina.core.StandardThreadExecutor"/>    

Relevant attribute description:

Connector

It is used to create a connector instance. By default, server.xml configures two connectors, one supports the HTTP protocol and the other supports the AJP protocol.

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

1) port: Port number, Connector is used to create a server Socket and monitor it to wait for the client to request a connection. If this property is set to 0, Tomcat will randomly select an available port number for the current Connector to use.

2) protocol: the access protocol supported by the current Connector. The default is HTTP/1.1, and an automatic switching mechanism is used to select a JAVA NIO-based linker or a local APR-based linker (based on whether the local Tomcat library is included). If you do not want to use the above automatic switching mechanism, but specify the protocol explicitly, the following values ​​can be used.

Http protocol:

org.apache.coyote.http11.Http11NioProtocol , the non-blocking Java NIO linker

org.apache.coyote.http11.Http11Nio2Protocol , non-blocking JAVA NIO2 linker

org.apache.coyote.http11.Http11AprProtocol , the APR linker

AJP agreement:

org.apache.coyote.ajp.AjpNioProtocol , the non-blocking Java NIO linker

org.apache.coyote.ajp.AjpNio2Protocol , non-blocking JAVA NIO2 linker

org.apache.coyote.ajp.AjpAprProtocol , the APR linker

3) connectionTimeOut: The waiting timeout time after the Connector receives the connection, in milliseconds. -1 means no timeout.

4) redirectPort: The current Connector does not support SSL requests. A request is received, and it also complies with the security constraint. SSL transmission is required, and Catalina automatically redirects the request to the specified port.

5) executor: Specify the name of the shared thread pool, or configure the internal thread pool through attributes such as maxThreads and minSpareThreads.

6) URIEncoding: It is used to specify the character encoding of the encoded URI. The default encoding of the Tomcat8.x version is UTF-8, and the default encoding of the Tomcat7.x version is ISO-8859-1.

Engine

Engine, as the top-level element of the Servlet engine, can be embedded inside: Cluster, Listener, Realm, Valve and Host.

<Engine name="Catalina" defaultHost="localhost"> 
...
</Engine>

1) name: used to specify the name of the Engine, the default is Catalina. This name will affect part of Tomcat's storage path (such as temporary files).

2) defaultHost: The name of the virtual host used by default. When the host requested by the client is invalid, it will be handled by the default virtual host, which is localhost by default. When parsing the ip address, first find the right host from the host list according to the host set by defaultHost to jump, if there is no corresponding one from the host list, if there is no one in the list, then it will not be accessed.

In addition, the Realn tag is also included in the default configuration file, as follows:

<Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>

<GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
 </GlobalNamingResources>

<Realm>Labels are used to configure user permissions.

Let me talk about the authority management of tomcat first. Because multiple web projects can be configured in tomcat, and tomcat creates management pages for the management of these projects, that is, the project pages of the host-manager and manager folders under the default webapps. In order to ensure security, access to these two projects requires Set permissions, but if it is cumbersome and troublesome to set permissions separately for each new user, several different permissions are defined in tomcat, and we can configure "roles" (which can be regarded as a collection of specific permissions) and " User" (set login name, password, and role association), and then you can access the management page through the customized "user". The configuration of "role" and "user" can be configured in tomcat-users.xml by default. When tomcat starts, it will check the permissions through the Realm tag in server.xml in the conf directory.

<Realm>Support multiple Realm management methods:

1 JDBCRealm user authorization information is stored in a relational database, and information verification is obtained through the JDBC driver

2 DataSourceRealm User authorization information is stored in about-type data, and information verification is obtained by configuring JDBC data sources through JNDI

3 JNDIRealm user authorization information is stored in the LDAP-based directory service server, obtained and verified through the JNDI driver

4 UserDatabaseRealm The default configuration method, the information is stored in the XML document conf/tomcat-users.xml

5 MemoryRealm User information is stored in the collection of memory, and the data of the object collection comes from the xml document conf/tomcat-users.xml

6 JAASRealm access authorization information through the JAAS framework

It can be seen from the above code block that Realm is configured in the default UserDatabaseRealm mode. And its resourceName corresponds to the tomcat-users.xml file in the conf directory configured <GlobalNamingResources>in .

If Realm is configured under Engine, then this configuration will be shared among all Hosts under the current Engine. Similarly, if Realm is configured in Host, it will be shared among all Contexts under the current Host. The bottom layer will overwrite the configuration of the same resource by the upper layer.

Host

Used to configure a virtual host, it supports the following embedded elements: Alias, Cluster, Listener, Valve, Realm, Context. Multiple Hosts can be configured under an Engine tag.

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
...
</Host>

Property description:

1) name: The common network name of the current Host, which must be consistent with the registration information on the DNS server. The Host included in the Engine must have a name consistent with the defaultHost setting of the Engine.

2) appBase: The application base directory of the current Host, and the web applications deployed on the current Host are all under this directory (it can be an absolute directory or a relative path). Defaults to webapps.

3) unpackWARs: If set to true, the Host will decompress the war package under the appBase directory into a directory when it starts. Set to false, the Host will start directly from the war file.

4) autoDeploy: Control whether tomcat periodically detects and automatically deploys new or changed web applications during runtime.

Context

Used to configure a web application.

<Context docBase="myApp" path="/myApp"> 
.... 
</Context>

Property description:

1) docBase: Web application directory or deployment path of War package. It can be an absolute path or a relative path relative to the Host appBase.

2) path: Context path of the web application. If our Host name is localhost, then the root path accessed by the web application is: http://localhost:8080/myApp. The embedded elements it supports are: CookieProcessor, Loader, Manager, Realm, Resources, WatchedResource, JarScanner, Valve.

tomcat-user.xml (permission management)

The realm tag above mentioned that this file is used to set user permissions in conjunction with the realm tag, so let's take a look at how to set it up.

First look at the default configuration

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>

<tomcat-users>There are two sub-tags in the tag, <role>and <user>, role is used to set the "role", and user is used to set the login "user". The management page is the host-manager and manager directories under webapps to manage all hosts and all web projects respectively. If we only open the commented part, we still cannot access the management page, because tomcat has set a specific permission name, first is manager:

manager-gui allows access to the html interface (ie the URL path is /manager/html/*)

manager-script allows access to the plain text interface (i.e. the URL path is /manager/text/*)

manager-jmx allows access to the JMX proxy interface (ie the URL path is /manager/jmxproxy/*)

manager-status allows access to the Tomcat read-only status page (ie the URL path is /manager/status/*)

For host-manager:

admin-gui allows access to the html interface (ie the URL path is /host-manager/html/*)

admin-script allows access to the plain text interface (i.e. the URL path is /host-manager/text/*)

admin-jmx allows access to the JMX proxy interface (ie the URL path is /host-manager/jmxproxy/*)

admin-status allows access to the Tomcat read-only status page (ie the URL path is /host-manager/status/*)

If we want a role to directly access these two project pages, we can configure roles as the following settings, and then we can access the manager and host-manager pages.

<user username="tomcat" password="tomcat" roles="admin-script,admin-gui,manager-gui,manager-script"/>

Web.xml (not commonly used)

web.xml is rarely used anymore, so this part of the content can be simply understood. The web.xml file is divided into the conf of the tomcat installation directory and the WEB-INF directory of each project. The configuration under conf is the global configuration, all web projects will be affected, while the configuration under WEB-INF will only affect the current project, but if it conflicts with the web.xml configuration under conf, then the configuration in conf will be overwritten.

ServletContext initializes global parameters

K, V key-value pair. You can use the javax.servlet.ServletContext.getInitParameter() method to get parameter values ​​in your application.

<context-param> 
  <param-name>contextConfigLocation</param-name> 
  <param-value>classpath:applicationContext-*.xml</param-value> 
  <description>Spring Config File Location</description> <
</context-param>  

session settings

Used to configure web application sessions, including timeout, cookie configuration, and session tracking mode. It will override configuration in server.xml and context.xml.

<session-config>
  <session-timeout>30</session-timeout> 
  <cookie-config> 
    <name>JESSIONID</name> 
    <domain>www.itcast.cn</domain> 
    <path>/</path> 
    <comment>Session Cookie</comment> 
    <http-only>true</http-only> 
    <secure>false</secure> 
    <max-age>3600</max-age> 
  </cookie-config> 
  <tracking-mode>COOKIE</tracking-mode> 
</session-config>

1) session-timeout: session timeout, unit: minute

2) cookie-config: used to configure session tracking cookies

name: the name of the cookie

domain: the domain name of the cookie

path: the path of the cookie

comment: comment

http-only: The cookie can only be accessed through HTTP, and cannot be read or modified by JS. This item can increase the security of website access.

secure: This cookie can only be passed to the server over HTTPS connections, while HTTP connections will not pass this information. Note that it is passed from the browser to the server, and the cookie object on the server side is not affected by this item.

max-age: Indicates the lifetime of the cookie in seconds, the default is -1, which means it is a session cookie, and it will disappear when the browser is closed.

3) tracking-mode: used to configure the session tracking mode, the tracking mode supported in Servlet3.0 version: COOKIE, URL, SSL

A. COOKIE : Tracking sessions through HTTP Cookies is the most commonly used session tracking mechanism, and the Servlet specification also requires that all Servlet specifications need to support Cookie tracking.

B. URL: URL rewriting is the most basic session tracking mechanism. When the client does not support cookies, URL rewriting can be used. When the URL tracking mode is used, the request path needs to contain session identification information, and the Servlet container will set the requested session information according to the session identification in the path. Such as: http://www.myserver.com/user/index.html;jessionid=1234567890.

C. SSL : For SSL requests, the request session ID is determined by the SSL session ID.

Servlet configuration

The configuration of Servlet is mainly composed of two parts, servlet and servlet-mapping:

<servlet> 
    <servlet-name>myServlet</servlet-name> 
    <servlet-class>cn.itcast.web.MyServlet</servlet-class> 
    <init-param> 
        <param-name>fileName</param-name> 
        <param-value>init.conf</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
    <enabled>true</enabled> 
</servlet> 
<servlet-mapping> 
    <servlet-name>myServlet</servlet-name> 
    <url-pattern>*.do</url-pattern> 
    <url-pattern>/myservet/*</url-pattern> 
</servlet-mapping>        

1) servlet-name: Specify the name of the servlet, which is unique in web.xml.

2) servlet-class: used to specify the servlet class name

3) init-param: It is used to specify the initialization parameters of the servlet, which can be obtained through HttpServlet.getInitParameter in the application.

4) load-on-startup: Used to control the loading order of Servlets when the Web application starts. If the value is less than 0, the servlet will not be loaded when the web application starts, and it will be loaded when it is accessed for the first time.

5) enabled: true, false. If it is false, it means that the Servlet does not process any requests.

6) url-pattern: It is used to specify the URL expression, and one servlet-mapping can configure multiple url-patterns at the same time.

File upload configuration in Servlet:

<servlet> 
    <servlet-name>uploadServlet</servlet-name> 
    <servlet-class>cn.itcast.web.UploadServlet</servlet-class>                     
    <multipart-config> 
        <location>C://path</location> 
        <max-file-size>10485760</max-file-size> 
        <max-request-size>10485760</max-request-size> 
        <file-size-threshold>0</file-size-threshold> 
    </multipart-config> 
</servlet>

1) location: store the generated file address.

2) max-file-size: The maximum file size allowed to be uploaded. The default value is -1, which means no limit.

3) max-request-size: The maximum number of multi/form-data requests, the default value is -1, which means unlimited.

4) file-size-threshold: When the quantity is greater than this value, the content will be written into the file.

Listener configuration

Listener is used to listen to events in servlets, such as context, request, and session object creation, modification, and deletion, and trigger response events. Listener is the implementation of observer mode, which is mainly used in servlet to monitor the life cycle of context, request and session objects. There are 8 Listeners defined in the servlet2.5 specification. When starting, the execution order of ServletContextListener is consistent with the configuration order in web.xml, and the execution order is reversed when stopping.

<listener> 
    <listener- class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener>

Filter configuration

fifilter is used to configure web application filters to filter resource requests and responses. Often used for authentication, logging, encryption, data conversion and other operations, the configuration is as follows:

<filter> 
    <filter-name>myFilter</filter-name> 
    <filter-class>cn.itcast.web.MyFilter</filter-class> 
    <async-supported>true</async-supported> 
    <init-param> 
        <param-name>language</param-name> 
        <param-value>CN</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>myFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

1) filter-name: used to specify the filter name, in web.xml, the filter name must be unique.

2) filter-class: The fully qualified class name of the filter, which must implement the Filter interface.

3) async-supported: Whether the filter supports asynchronous

4) init-param: used to configure the initialization parameters of the Filter, multiple configurations can be configured, and can be obtained through FilterConfig.getInitParameter

5) url-pattern: Specify the URL that the filter needs to intercept.

Welcome page configuration

<welcome-file-list> 
    <welcome-file>index.html</welcome-file> 
    <welcome-file>index.htm</welcome-file> 
    <welcome-file>index.jsp</welcome-file> 
</welcome-file-list>

The order in which requests are tried, top to bottom.

Error page configuration

error-page is used to configure the page that the web application is redirected to when accessing an exception. It supports HTTP response code and exception type.

<error-page> 
    <error-code>404</error-code> 
    <location>/404.html</location> 
</error-page> 
<error-page> 
    <error-code>500</error-code> 
    <location>/500.html</location> 
</error-page> 
<error-page> 
    <exception-type>java.lang.Exception</exception-type>                 
    <location>/error.jsp</location> 
</error-page>

Security and Optimization

Safety

configuration security

1) Delete all files in the webapps directory and disable the tomcat management interface;

2) Comment or delete all user permissions in the tomcat-users.xml file;

3) Change or disable the command to close tomcat; the server.xml of tomcat defines the management port that can directly close the Tomcat instance (8005 by default). After connecting to the port through telnet, enter SHUTDOWN (this is the default shutdown command) to close the Tomcat instance (note that although the instance is closed at this time, the process still exists). Since Tomcat's ports and instructions are closed by default, it is very simple. The default port is 8005, and the command is SHUTDOWN.

Solution 1: Change the port number

<Server port="8456" shutdown="itcast_shut">

Solution 2: Disable port 8005 and set it to -1.

<Server port="-1" shutdown="SHUTDOWN">

4) Define the error page. If it is not defined, the code class name and location will be displayed after an exception occurs, which will leak the directory structure. Define error pages 404.html and 500.html in the webapps/ROOT directory; then configure them in tomcat/conf/web.xml, and configure the error page:

<error-page> 
    <error-code>404</error-code> 
    <location>/404.html</location> 
</error-page> 
<error-page> 
    <error-code>500</error-code> 
    <location>/500.html</location> 
</error-page>

application security

Application security means that some privacy pages should only be accessed by logged-in users or administrator users, and these pages should be blocked when the permissions are insufficient. Interceptors or some security frameworks, such as SpringSecurity and Shiro, can be used.

transport security

The traditional network application protocol HTTP is not secure. At this time, HTTPS can be used instead. It adds SSL/TLS on the basis of HTTP to encrypt data and protect exchanged data from leakage and theft.

The difference between HTTPS and HTTP is mainly in the following four points:

1) The HTTPS protocol needs to apply for an SSL certificate from the certificate authority CA, and then bind it to the domain name. HTTP does not need to apply for a certificate;

2) HTTP is a hypertext transfer protocol, which belongs to the application layer information transmission, and HTTPS is a transfer protocol with SSL encryption and transmission security, which encrypts data transmission, which is equivalent to an upgraded version of HTTP;

3) HTTP and HTTPS use completely different connection methods and different ports. The former is 8080 and the latter is 8443.

4) The HTTP connection is very simple and stateless; the HTTPS protocol is a network protocol constructed by the SSL+HTTP protocol that can perform encrypted transmission and identity authentication, which is safer than the HTTP protocol.

Advantages of HTTPS protocol:

1) Improve the ranking of the website, which is beneficial to SEO. Google has publicly stated that two sites are equal in terms of search results, and that if a site has SSL enabled, it may get a slightly higher rating than a site without SSL, and Baidu has also shown that it is friendly to sites with SSL installed. Therefore, enabling SSL in the content on the website has obvious SEO advantages.

2) Encrypt private information to prevent traffic hijacking. Especially for websites that involve private information, large-scale data leakage incidents on the Internet occur frequently, and it is imperative for websites to encrypt information. Floor 1, Jinyanlong Office Building, Jiancaicheng West Road, Changping District, Beijing Tel: 400-618-9090

3) The browser is trusted. Since the major mainstream browsers have strongly supported the HTTPS protocol, websites accessing HTTP will prompt an "unsafe" warning message.

performance optimization

Performance Testing

ApacheBench (ab) is a testing tool for Apache Server benchmarks. Users test the service capability of Apache Server (the number of requests processed per second). It can not only test Apache, but also test Tomcat, Nginx, lighthttp, IIS and other servers .

Installation: yum install httpd-tools

执行:b -n 1000 -c 100 -p data.json -T application/json http://localhost:9000/course/search.do?page=1&pageSize=10

Parameter Description:

If this request needs to carry Post data, you need to customize a file to save this data, generally use json format to save the transmission

Execution result section:

Parameter Description:

Key parameters that need attention:

JVM optimization

Because Tomcat is a Java server, its optimization can be attributed to the optimization of the JVM, and the optimization of Tomcat on the JVM can be divided into the selection of the garbage collector and some parameter configurations. There is no need to elaborate on the configuration of the garbage collector and related parameters here. Here we only introduce how to carry the configuration we want when Tomcat starts.

Under windows: modify the bin/catalina.bat file, add in the first line: set JAVA_OPTS=-server -Dfile.encoding=UTF-8 specific configuration

Under linux: modify the bin/catalina.sh file, add in the first line: JAVA_OPTS=" -server specific configuration"

Tomcat configuration optimization

The configuration of the connector is the key to determine the performance of Tomcat. Under normal circumstances, it is enough to use the default one, but when the program is difficult, it needs to be manually configured to improve efficiency. The complete configuration is as follows:

<Connector port="8080" 
    protocol="HTTP/1.1" 
    executor="tomcatThreadPool" 
    maxThreads="1000" 
    minSpareThreads="100" 
    acceptCount="1000" 
    maxConnections="1000" 
    connectionTimeout="20000" 
    compression="on" 
    compressionMinSize="2048" 
    disableUploadTimeout="true" 
    redirectPort="8443" 
    URIEncoding="UTF-8" />

Related parameters:

maxThreads: indicates the maximum number of threads that Tomcat can create;

minSpareThreads: The minimum number of idle threads, the number of threads created when Tomcat is initialized, this value should be less than maxThreads, the default value is 4;

acceptCount: Specifies the number of requests that can be placed in the processing queue when all available threads for processing requests are used. Requests exceeding this number will not be processed, and the default is 10;

maxConnections: The maximum number of connections the server will accept and process at any given time.

connectionTimeout: Network connection timeout, in milliseconds, if set to "0", it means never timeout, it is not recommended to set this way;

compression: The default is off, and when it is turned on, the connector uses HTTP/1.1 GZIP compression in an attempt to save server bandwidth. Turning off automatically makes a trade-off between compression and transmission.

compressionMinSize: When compression is enabled, you can use this to configure the minimum amount of data to be compressed. The default is "2048".

disableUploadTimeout: Whether to use the timeout mechanism when uploading files. It is enabled by default and is determined by ConnectionTimeout. If it is false, it will only be disconnected after the time set by connectionUploadTimeout.

redirectPort: If this connector supports non-SSL requests, and if a matching request is received that requires SSL transport, Catalina will automatically redirect the request to the port number specified here.

For other parameters, please refer to the blog tomcat(4) connector .

If you just want a simple configuration, you can only configure maxConnections, maxThreads, acceptCount.

Tomcat additional function WebSocket

When we browse the web, we generally use the HTTP protocol or the HTTPS protocol. This method is a "request-response" mode, that is, it only supports sending requests from the client, and the server processes them after receiving them, and then returns a response , but cannot actively send data to the client, so it is difficult or even impossible to implement in some scenarios, such as real-time chat in a chat room, some people may say that the processing in the servlet is directly sent to the client to send the message. That's fine, but because of the "request-response" mode, when other clients do not communicate with the server for a period of time, the connection will be disconnected, and the server will not be able to forward the message. WebSocket is a persistent connection protocol based on HTTP, and it is a two-way channel, which enables the server to actively send messages to the client.

WebSocket request process

There are several differences between WebSocket requests and ordinary HTTP requests:

\1. The address of the GET request is not similar to http://, but an address starting with ws://;

\2. The request header Connection: Upgrade and the request header Upgrade: websocket indicate that this connection will be converted to a WebSocket connection;

\3. Sec-WebSocket-Key is used to identify this connection, it is a ciphertext encoded by BASE64, and the server is required to respond with a corresponding encrypted Sec-WebSocket-Accept header information as a response;

\4. Sec-WebSocket-Version specifies the protocol version of WebSocket;

\5. The HTTP101 status code indicates that the server has recognized and switched to the WebSocket protocol, and Sec-WebSocket-Accept is the information calculated from the same secret key between the server and the client.

Version 7.0.5 of Tomcat began to support WebSocket and implemented the Java WebSocket specification (JSR356), while before version 7.0.5 (after 7.0.2), it used a custom API, namely WebSocketServlet implementation. A Java WebSocket application consists of a series of WebSocketEndpoints. Endpoint is a java object that represents one end of a WebSocket connection. For the server, we can regard it as an interface for processing specific WebSocket messages, just like Servlets and http requests. We can define Endpoint in two ways:

1). The first is programmatic, that is, inheriting the class javax.websocket.Endpoint and implementing its methods.

2). The second is the annotation type, which defines a POJO and adds @ServerEndpoint related annotations. The Endpoint instance is created during the WebSocket handshake, and is valid during the connection between the client and the server, and ends when the connection is closed. The methods related to its life cycle are clearly defined in the Endpoint interface, and the specification implementer ensures that the relevant methods of the instance are called at each stage of the life cycle. The lifecycle methods are as follows:

By adding a MessageHandler message processor to the Session to receive messages, when using annotations to define Endpoints, we can also specify the method of receiving messages through the @OnMessage annotation. Sending messages is done by RemoteEndpoint, and its instance is maintained by Session. According to the usage, we can get the instance of synchronous message sending through Session.getBasicRemote, and then call its sendXxx() method to send the message. We can get asynchronous message through Session.getAsyncRemote Send instance.

title

Guess you like

Origin blog.csdn.net/Tyson0314/article/details/130487696